Commit f6c6495b authored by eliechoufani's avatar eliechoufani
Browse files

first commit

parent b8a44fd2
name: API Addresses Open Data France
type: module
description: 'API connector for Geo addresses data in France, geo.api.gouv.fr'
package: Geo API gouv.fr
version: 8.x
core: 8.x
api_adresses_open_data_france_js:
js:
js/api_adresses_open_data_france.js: {}
dependencies:
- core/drupal
- core/jquery
- core/drupalSettings
- core/jquery.once
- core/drupal.ajax
- core/views.ajax
- core/jquery.ui
- core/jquery.ui.effects.core
- core/jquery.ui.autocomplete
api_adresses_open_data_france_css:
version: 1.x
css:
theme:
css/api_adresses_open_data_france.css: {}
\ No newline at end of file
<?php
/**
* @param $variables
*/
function api_adresses_open_data_france_preprocess_page(&$variables){
$config = \Drupal::config('api_adresses_open_data_france.settings');
$field_address_id = $config->get('field_sirene_id');
$field_postal_code_id = $config->get('field_postal_code_id');
$field_city_id = $config->get('field_city_id');
//Add the JS library
$variables['#attached']['library'][] = 'api_adresses_open_data_france/api_adresses_open_data_france_js';
//Pass variables to Drupal.Settings
$variables['#attached']['drupalSettings']['api_adresses_open_data_france']['field_address_id'] = $field_address_id;
$variables['#attached']['drupalSettings']['api_adresses_open_data_france']['field_postal_code_id'] = $field_postal_code_id;
$variables['#attached']['drupalSettings']['api_adresses_open_data_france']['field_city_id'] = $field_city_id;
}
\ No newline at end of file
api_adresses_open_data_france.settings:
path: '/admin/config/api_adresses_open_data_france/settings'
defaults:
_form: '\Drupal\api_adresses_open_data_france\Form\GeoAddressesFrFieldsConfig'
_title: 'Geo API Addresses France Settings'
requirements:
_permission: 'administer site configuration'
api_adresses_open_data_france.address_autocomplete:
path: '/api_adresses_open_data_france/address-autocomplete'
defaults:
_controller: '\Drupal\api_adresses_open_data_france\Controller\AddressAjaxController::address_autocomplete'
_title: 'Autocomplete'
_format: json
requirements:
_access: 'TRUE'
\ No newline at end of file
(function ($, Drupal, drupalSettings) {
Drupal.behaviors.APISireneDataFrBehavior = {
attach: function (context, settings) {
$(document).ready(function() {
var field_address_id = drupalSettings.api_adresses_open_data_france.field_address_id;
var field_postal_code_id = drupalSettings.api_adresses_open_data_france.field_postal_code_id;
var field_city_id = drupalSettings.api_adresses_open_data_france.field_city_id;
$('#'+field_address_id).autocomplete({
source : function(requete, reponse){ // les deux arguments représentent les données nécessaires au plugin
$.ajax({
url : Drupal.url('api_adresses_open_data_france/address-autocomplete'), // on appelle le script JSON
dataType : 'json', // on spécifie bien que le type de données est en JSON
type: "POST",
data : {
//variable envoyé avec la requête vers le serveur
name_startsWith : $('#'+field_address_id).val(), // on donne la chaîne de caractère tapée dans le champ de recherche
},
success : function(donnee){
//donnee est la variable reçu du serveur avec les résultats
reponse($.map(donnee, function(objet){
// on retourne cette forme de suggestion avec ces datas
return {
'label':objet.properties.label,
'value':objet.properties.name,
'postcode':objet.properties.postcode,
'id':objet.properties.id,
'city':objet.properties.city,
};
}));
}
});
}
});
$('#'+field_address_id).on( "autocompleteselect", function( event, ui ) {
var postcode = ui.item.postcode;
var city = ui.item.city;
$('#'+field_postal_code_id).val(postcode);
$('#'+field_city_id).val(city);
});
});
}
};
})(jQuery, Drupal, drupalSettings);
\ No newline at end of file
<?php
namespace Drupal\api_adresses_open_data_france\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Serialization\JSON;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\api_adresses_open_data_france\GeoAPIGouvFrManager;
class AddressAjaxController extends ControllerBase {
//function for autocomplete
public function address_autocomplete(Request $request){
$return = []; //our variable to fill with data to return to autocomplete result
$search_string = \Drupal::request()->request->get('name_startsWith');
$type = "housenumber"; // can be housenumber, street, locality or municipality.
$geoApi = new GeoAPIGouvFrManager();
$return = $geoApi->searchPlace($geoApi->buildOptionsSearchAutocomplete($search_string, $type, 10));
return new JsonResponse(json_encode($return['features']), 200, [], true);
}
//search function
public function address_autocomplete_search(){
//same logic as first function
$return = [];
return new JsonResponse(json_encode($return), 200, [], true);
}
}
\ No newline at end of file
<?php
namespace Drupal\api_adresses_open_data_france\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure API Sirene Open Data fields settings.
*/
class GeoAddressesFrFieldsConfig extends ConfigFormBase {
/**
* Config settings.
*
* @var string
*/
const SETTINGS = 'api_adresses_open_data_france.settings';
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'api_adresses_open_data_france_config_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
static::SETTINGS,
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config(static::SETTINGS);
$form['field_address_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Address ID'),
'#default_value' => $config->get('field_address_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_postal_code_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Postal Code ID'),
'#default_value' => $config->get('field_postal_code_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_city_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field City ID'),
'#default_value' => $config->get('field_city_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Retrieve the configuration.
$this->configFactory->getEditable(static::SETTINGS)
// Set the submitted configuration setting.
->set('field_address_id', $form_state->getValue('field_address_id'))
->set('field_postal_code_id', $form_state->getValue('field_postal_code_id'))
->set('field_city_id', $form_state->getValue('field_city_id'))
->save();
parent::submitForm($form, $form_state);
}
}
<?php
namespace Drupal\api_adresses_open_data_france;
use Drupal\Component\Serialization\Json;
use GuzzleHttp\Exception\RequestException;
/**
* Basic manager of module.
*/
class GeoAPIGouvFrManager {
/**
* The request url of Sendinblue api.
*/
const API_URL = 'https://api-adresse.data.gouv.fr';
public $client;
/**
* Constructor.
*/
public function __construct() {
if (!function_exists('curl_init')) {
$msg = 'Geo API gouv.fr requires CURL module';
\Drupal::logger('api_adresses_open_data_france')->error($msg);
return;
}
$this->client = \Drupal::httpClient();
}
/**
* Do CURL request with authorization.
*
* @param string $resource
* A request action of api.
* @param string $method
* A method of curl request.
* @param Array $inputs
* A data of curl request.
*
* @return array
* An associate array with respond data.
*/
private function executeCurl($resource, $method, $inputs) {
if (!function_exists('curl_init')) {
$msg = 'Geo API gouv.fr requires CURL module';
\Drupal::logger('api_adresses_open_data_france')->error($msg);
return NULL;
}
$api_url = self::API_URL . "/" . $resource;
$options = [
'headers' => [
'Content-Type' => 'application/json'
],
];
if (!empty($inputs)) {
if($method == 'GET'){
$api_url.= '?' . self::arrayKeyfirst($inputs) . '=' . array_shift($inputs);
foreach($inputs as $param => $value){
$api_url.= '&' . $param . '=' . $value;
}
}else{
//POST request send data in array index form_params.
//$options['body'] = $inputs;
}
}
try {
$clientRequest = $this->client->request($method, $api_url, $options);
$body = $clientRequest->getBody();
} catch (RequestException $e) {
\Drupal::logger('api_adresses_open_data_france')->error('Curl error: @error', ['@error' => $e->getMessage()]);
}
return Json::decode($body);
}
/**
* Get Request of API.
*
* @param string $resource
* A request action.
* @param string $input
* A data of curl request.
*
* @return array
* A respond data.
*/
public function curlGet($resource, $inputs) {
return $this->executeCurl($resource, "GET", $inputs);
}
/**
* Post Request of API.
*
* @param string $resource
* A request action.
* @param string $inputs
* A data of curl request.
*
* @return array
* A respond data.
*/
public function curlPost($resource, $inputs) {
return $this->executeCurl($resource, "POST", $inputs);
}
/**
* Search place by street number, city name, street name...
*
* @param array $options
* An array of search options.
*
* @return array
* An array of search results.
*/
public function searchPlace($options) {
return $this->curlGet("search", $options);
}
/**
* Get campaigns by type.
*
* @param string $type
* A campaign type.
*
* @return array
* An array of options.
*/
public function buildOptionsSearchAutocomplete($searchString, $type, $limit = 5, $autocomplete = 1) {
$options = [
"q" => $searchString,
"type" => $type,
"autocomplete" => $autocomplete,
"limit" => $limit,
];
return $options;
}
/**
* Function to return first element of the array, compatability with PHP 5, note that array_key_first is only available for PHP > 7.3.
*
* @param array $array
* Associative array.
*
* @return string
* The first key data.
*/
public static function arrayKeyfirst($array){
if (!function_exists('array_key_first')) {
foreach($array as $key => $unused) {
return $key;
}
return NULL;
}else{
return array_key_first($array);
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment