Skip to content
Snippets Groups Projects
Commit 4d7abc1e authored by elie choufani's avatar elie choufani
Browse files

dev release

parent 452f6483
No related branches found
No related tags found
No related merge requests found
name: API Sirene Open Data France
type: module
description: 'API connector for entreprises data in France, entreprise.data.gouv.fr'
package: Entreprise Data gouv.fr
version: 8.x
core: 8.x
api_sirene_open_data_france_test_js:
js:
js/api_sirene_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_sirene_open_data_france_test_css:
version: 1.x
css:
theme:
css/api_sirene_open_data_france.css: {}
\ No newline at end of file
<?php
/**
* @param $variables
*/
function api_sirene_open_data_france_preprocess_page(&$variables){
$config = \Drupal::config('api_sirene_open_data_france.settings');
$field_sirene_id = $config->get('field_sirene_id');
$field_company_name_id = $config->get('field_company_name_id');
$field_company_address_id = $config->get('field_company_address_id');
$field_company_postal_code_id = $config->get('field_company_postal_code_id');
$field_company_city_id = $config->get('field_company_city_id');
//Add the JS library
$variables['#attached']['library'][] = 'api_sirene_open_data_france/api_sirene_open_data_france_test_js';
//Pass variables to Drupal.Settings
$variables['#attached']['drupalSettings']['api_sirene_open_data_france']['field_sirene_id'] = $field_sirene_id;
$variables['#attached']['drupalSettings']['api_sirene_open_data_france']['field_company_name_id'] = $field_company_name_id;
$variables['#attached']['drupalSettings']['api_sirene_open_data_france']['field_company_address_id'] = $field_company_address_id;
$variables['#attached']['drupalSettings']['api_sirene_open_data_france']['field_company_postal_code_id'] = $field_company_postal_code_id;
$variables['#attached']['drupalSettings']['api_sirene_open_data_france']['field_company_city_id'] = $field_company_city_id;
}
\ No newline at end of file
api_sirene_open_data_france.settings:
path: '/admin/config/api_sirene_open_data_france/settings'
defaults:
_form: '\Drupal\api_sirene_open_data_france\Form\SireneOAFrFieldsConfig'
_title: 'API Sirene Open Data France Settings'
requirements:
_permission: 'administer site configuration'
api_sirene_open_data_france.entreprise_data_autocomplete:
path: '/api_sirene_open_data_france/entreprise-data-autocomplete'
defaults:
_controller: '\Drupal\api_sirene_open_data_france\Controller\EntrepriseAjaxController::entreprise_data_autocomplete'
_title: 'Search'
_format: json
requirements:
_access: 'TRUE'
(function ($, Drupal, drupalSettings) {
Drupal.behaviors.APISireneDataFrBehavior = {
attach: function (context, settings) {
var field_sirene_id = drupalSettings.api_sirene_open_data_france.field_sirene_id;
var field_company_name_id = drupalSettings.api_sirene_open_data_france.field_company_name_id;
var field_company_address_id = drupalSettings.api_sirene_open_data_france.field_company_address_id;
var field_company_postal_code_id = drupalSettings.api_sirene_open_data_france.field_company_postal_code_id;
var field_company_city_id = drupalSettings.api_sirene_open_data_france.field_company_city_id;
$(document).ready(function() {
//--> search by Siret ou Siren
$('#'+field_sirene_id).autocomplete({
source : function(requete, reponse){ // les deux arguments représentent les données nécessaires au plugin
$.ajax({
url : Drupal.url('api_sirene_open_data_france/entreprise-data-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
siret_sirene : $('#'+field_sirene_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){
var label = "";
var value = "";
var nom = "";
var numero_voie = "";
var type_voie = "";
var libelle_voie = "";
var code_postal = "";
var libelle_commune = "";
if(typeof objet.unite_legale === 'object' && objet.unite_legale != null) {
//console.log("dans objet unite_legale");
label = objet.unite_legale.denomination + " (" + objet.code_postal + ")";
nom = objet.unite_legale.denomination;
value = objet.siret;
numero_voie = objet.numero_voie;
type_voie = objet.type_voie;
libelle_voie = objet.libelle_voie;
code_postal = objet.code_postal;
libelle_commune = objet.libelle_commune;
}else{
//console.log("else not in objet unite_legale");
label = objet.denomination + " (" + objet.etablissement_siege.code_postal + ")";
value = objet.siren;
nom = objet.denomination;
numero_voie = objet.etablissement_siege.numero_voie;
type_voie = objet.etablissement_siege.type_voie;
libelle_voie = objet.etablissement_siege.libelle_voie;
code_postal = objet.etablissement_siege.code_postal;
libelle_commune = objet.etablissement_siege.libelle_commune;
}
// on retourne cette forme de suggestion avec ces datas
return {
'label': label,
'value': value,
'nom': nom,
'numero_voie': numero_voie,
'type_voie': type_voie,
'libelle_voie': libelle_voie,
'code_postal': code_postal,
'libelle_commune': libelle_commune,
};
}));
}
});
}
});
$('#'+field_sirene_id).on( "autocompleteselect", function( event, ui ) {
var nom = ui.item.nom;
var numero_voie = ui.item.numero_voie;
var type_voie = ui.item.type_voie;
var libelle_voie = ui.item.libelle_voie;
var code_postal = ui.item.code_postal;
var libelle_commune = ui.item.libelle_commune;
$('#'+field_company_name_id).val(nom);
$('#'+field_company_address_id).val(numero_voie + " " + type_voie + " " + libelle_voie);
$('#'+field_company_postal_code_id).val(code_postal);
$('#'+field_company_city_id).val(libelle_commune);
});
//--> search by full_text : nom de l'entreprise
$('#'+field_company_name_id).autocomplete({
source : function(requete, reponse){ // les deux arguments représentent les données nécessaires au plugin
$.ajax({
url : Drupal.url('api_sirene_open_data_france/entreprise-data-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
query_name : $('#'+field_company_name_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){
var label = "";
var value = "";
var type_voie = "";
var numero_voie = "";
var libelle_voie = "";
var code_postal = "";
var libelle_commune = "";
label = objet.nom_raison_sociale + " (" + objet.code_postal + ")";
value = objet.nom_raison_sociale;
numero_voie = objet.numero_voie;
type_voie = objet.type_voie;
libelle_voie = objet.libelle_voie;
code_postal = objet.code_postal;
libelle_commune = objet.libelle_commune;
// on retourne cette forme de suggestion avec ces datas
return {
'label': label,
'value': value,
'type_voie': type_voie,
'numero_voie': numero_voie,
'libelle_voie': libelle_voie,
'code_postal': code_postal,
'libelle_commune': libelle_commune,
};
}));
}
});
}
});
$('#'+field_company_name_id).on( "autocompleteselect", function( event, ui ) {
var type_voie = ui.item.type_voie;
var numero_voie = ui.item.numero_voie;
var libelle_voie = ui.item.libelle_voie;
var code_postal = ui.item.code_postal;
var libelle_commune = ui.item.libelle_commune;
$('#'+field_company_address_id).val(numero_voie + " " + type_voie + " " + libelle_voie);
$('#'+field_company_postal_code_id).val(code_postal);
$('#'+field_company_city_id).val(libelle_commune);
});
});
}
};
})(jQuery, Drupal, drupalSettings);
\ No newline at end of file
<?php
namespace Drupal\api_sirene_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_sirene_open_data_france\EntrepriseDataApiManager;
class EntrepriseAjaxController extends ControllerBase {
//function for autocomplete
public function entreprise_data_autocomplete(Request $request){
$return = []; //our variable to fill with data to return to autocomplete result
$search = "sirene";
$search_string = \Drupal::request()->request->get('siret_sirene');
if(strlen($search_string) > 9) $search = "siret";
if($search_string == "") {
$search_string = \Drupal::request()->request->get('query_name');
$search = "full_text";
}
//$type = "housenumber"; // can be housenumber, street, locality or municipality.
$edataApi = new EntrepriseDataApiManager();
switch($search){
case 'sirene':
$return = $edataApi->searchBySirene($search_string);
break;
case 'siret':
$return = $edataApi->searchBySiret($search_string);
break;
case 'full_text':
$return = $edataApi->searchByName($search_string);
$return = $return['etablissement'];
break;
}
return new JsonResponse(json_encode($return), 200, [], true);
}
}
\ No newline at end of file
<?php
namespace Drupal\api_sirene_open_data_france;
use Drupal\Component\Serialization\Json;
use GuzzleHttp\Exception\RequestException;
/**
* Basic manager of module.
*/
class EntrepriseDataApiManager {
/**
* The request url of the API.
*/
const API_URLv1 = 'https://entreprise.data.gouv.fr/api/sirene/v1';
const API_URLv3 = 'https://entreprise.data.gouv.fr/api/sirene/v3';
public $client;
/**
* Constructor.
*/
public function __construct() {
if (!function_exists('curl_init')) {
$msg = 'Entreprise Data API requires CURL module';
\Drupal::logger('api_sirene_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, $api) {
if (!function_exists('curl_init')) {
$msg = 'Entreprise Data API requires CURL module';
\Drupal::logger('api_sirene_open_data_france')->error($msg);
return NULL;
}
if(is_array($resource)){
$api_url = $api;
foreach ($resource as $res){
$api_url.="/".$res;
}
}else{
$api_url = $api . "/" . $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_sirene_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, $api) {
return $this->executeCurl($resource, "GET", $inputs, $api);
}
/**
* 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, $api) {
return $this->executeCurl($resource, "POST", $inputs, $api);
}
public function searchBySiret($siret) {
$resources = [
"etablissements",
$siret,
];
return $this->curlGet($resources, [], self::API_URLv3);
}
public function searchBySirene($sirene) {
$resources = [
"unites_legales",
$sirene,
];
return $this->curlGet($resources, [], self::API_URLv3);
}
public function searchByName($name) {
$resources = [
"full_text",
$name,
];
return $this->curlGet($resources, [], self::API_URLv1);
}
/**
* 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);
}
}
}
<?php
namespace Drupal\api_sirene_open_data_france\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure API Sirene Open Data fields settings.
*/
class SireneOAFrFieldsConfig extends ConfigFormBase {
/**
* Config settings.
*
* @var string
*/
const SETTINGS = 'api_sirene_open_data_france.settings';
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'api_sirene_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_sirene_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Sirene ID'),
'#default_value' => $config->get('field_sirene_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_company_name_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Company Name ID'),
'#default_value' => $config->get('field_company_name_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_company_address_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Company Address ID'),
'#default_value' => $config->get('field_company_address_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_company_postal_code_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Company Postal Code ID'),
'#default_value' => $config->get('field_company_postal_code_id'),
'#description' => $this->t('Enter your form field\'s HTML ID without the hashtag sign (#)'),
];
$form['field_company_city_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Field Company City ID'),
'#default_value' => $config->get('field_company_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_company_name_id', $form_state->getValue('field_company_name_id'))
->set('field_sirene_id', $form_state->getValue('field_sirene_id'))
->set('field_company_address_id', $form_state->getValue('field_company_address_id'))
->set('field_company_postal_code_id', $form_state->getValue('field_company_postal_code_id'))
->set('field_company_city_id', $form_state->getValue('field_company_city_id'))
->save();
parent::submitForm($form, $form_state);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment