| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290 |
- <?php
- /**
- * Client API Lucca
- *
- * Fonctions utilitaires pour communiquer avec l'API Lucca
- * Configuration via variables d'environnement pour préprod/prod
- */
- // --- Configuration (change à l'env de préprod / prod via variables d'environnement) ---
- define('LUCCA_API_BASE', getenv('LUCCA_API_BASE') ?: 'https://siparh-livinweb.sandbox.eu1.luccasoftware.com');
- define('LUCCA_API_TOKEN', getenv('LUCCA_API_TOKEN') ?: 'ed29a0a8-d394-4c93-b4f7-222360f8b465');
- // --- Client HTTP minimal vers Lucca ---
- /**
- * Effectue une requête HTTP vers l'API Lucca avec gestion avancée des erreurs
- *
- * @param string $method Méthode HTTP (GET, POST, PUT, DELETE, etc.)
- * @param string $path Chemin de l'endpoint (ex: /users, /leaves)
- * @param array $query Paramètres de query string
- * @param mixed $body Corps de la requête (array ou string)
- * @param int $timeout Timeout en secondes
- * @param bool $debug Active le mode debug Lucca ($debug=true)
- * @return array [
- * 'code' => int,
- * 'body' => string,
- * 'data' => array|null (JSON décodé),
- * 'error' => string|null,
- * 'lucca_error' => string|null (X-Lucca-ErrorMessage header),
- * 'error_message' => string|null (ErrorMessage du body),
- * 'headers' => array,
- * 'curl_info' => array
- * ]
- */
- function lucca_request(string $method, string $path, array $query = [], $body = null, int $timeout = 20, bool $debug = false): array {
- // Ajout automatique du paramètre $debug si demandé
- if ($debug) {
- $query['$debug'] = 'true';
- }
-
- $url = rtrim(LUCCA_API_BASE, '/') . '/' . ltrim($path, '/');
- if (!empty($query)) {
- $url .= '?' . http_build_query($query);
- }
- $headers = [
- 'Accept: application/json',
- 'Content-Type: application/json',
- 'Authorization: lucca application=' . LUCCA_API_TOKEN,
- ];
- // --- CAS 1 : cURL dispo → version propre PROD
- if (function_exists('curl_init')) {
- $ch = curl_init($url);
- curl_setopt_array($ch, [
- CURLOPT_CUSTOMREQUEST => strtoupper($method),
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_HEADER => true, // ✅ Inclure les headers dans la réponse
- CURLOPT_HTTPHEADER => $headers,
- CURLOPT_TIMEOUT => 30,
- CURLOPT_CONNECTTIMEOUT => 10,
- CURLOPT_SSL_VERIFYPEER => false, // Pour test local/sandbox
- CURLOPT_SSL_VERIFYHOST => false, // Pour test local/sandbox
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_VERBOSE => false,
- ]);
- if ($body !== null) {
- curl_setopt($ch, CURLOPT_POSTFIELDS, is_string($body) ? $body : json_encode($body, JSON_UNESCAPED_UNICODE));
- }
-
- $response = curl_exec($ch);
- $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- $err = curl_error($ch);
- $errno = curl_errno($ch);
- $info = curl_getinfo($ch);
- curl_close($ch);
-
- // Séparer headers et body
- $response_headers = substr($response, 0, $header_size);
- $response_body = substr($response, $header_size);
-
- // ✅ Extraction du header X-Lucca-ErrorMessage
- $lucca_error = null;
- if (preg_match('/X-Lucca-ErrorMessage:\s*(.+)/i', $response_headers, $match)) {
- $lucca_error = trim($match[1]);
- }
-
- // ✅ Parser les headers en tableau
- $headers_array = [];
- foreach (explode("\r\n", $response_headers) as $line) {
- if (strpos($line, ':') !== false) {
- list($key, $value) = explode(':', $line, 2);
- $headers_array[trim($key)] = trim($value);
- }
- }
-
- // ✅ Décoder le body JSON
- $data = json_decode($response_body, true);
-
- // ✅ Extraire ErrorMessage du body si présent
- $error_message_field = null;
- if (is_array($data) && isset($data['ErrorMessage'])) {
- $error_message_field = $data['ErrorMessage'];
- }
-
- // Diagnostic détaillé cURL
- $error_curl = null;
- if ($errno !== 0) {
- $error_curl = "cURL Error #$errno: $err";
- } elseif ($code === 0) {
- $error_curl = "Connection failed - no response from server. Check network/firewall. URL: $url";
- }
-
- return [
- 'code' => (int)$code,
- 'body' => $response_body ?: '',
- 'data' => $data,
- 'error' => $error_curl,
- 'lucca_error' => $lucca_error,
- 'error_message' => $error_message_field,
- 'headers' => $headers_array,
- 'curl_info' => [
- 'url' => $info['url'] ?? $url,
- 'total_time' => $info['total_time'] ?? 0,
- 'namelookup_time' => $info['namelookup_time'] ?? 0,
- 'connect_time' => $info['connect_time'] ?? 0,
- ]
- ];
- }
- // --- CAS 2 : PAS de cURL → fallback file_get_contents (local Windows, test rapide)
- // $opts = [
- // 'http' => [
- // 'method' => strtoupper($method),
- // 'header' => implode("\r\n", $headers),
- // 'timeout' => $timeout,
- // 'ignore_errors' => true
- // ],
- // 'ssl' => [
- // 'verify_peer' => false, // TEST LOCAL SEULEMENT
- // 'verify_peer_name' => false // TEST LOCAL SEULEMENT
- // ]
- // ];
- // if ($body !== null) {
- // $opts['http']['content'] = is_string($body) ? $body : json_encode($body, JSON_UNESCAPED_UNICODE);
- // }
- // $context = stream_context_create($opts);
- // $start_time = microtime(true);
-
- // // Capture les erreurs PHP
- // $old_error_handler = set_error_handler(function($errno, $errstr) {
- // return true; // Supprime l'affichage de l'erreur
- // });
-
- // $response = file_get_contents($url, false, $context);
- // $last_error = error_get_last();
-
- // if ($old_error_handler) {
- // set_error_handler($old_error_handler);
- // } else {
- // restore_error_handler();
- // }
-
- // $elapsed_time = microtime(true) - $start_time;
- // $code = 0;
- // $error_message = null;
-
- // if ($response === false) {
- // $error_message = "file_get_contents failed";
- // if ($last_error) {
- // $error_message .= ": " . $last_error['message'];
- // }
- // $error_message .= " | allow_url_fopen=" . ini_get('allow_url_fopen');
- // }
-
- // foreach ($http_response_header ?? [] as $line) {
- // if (preg_match('#HTTP/.* ([0-9]+)#', $line, $m)) {
- // $code = (int)$m[1];
- // break;
- // }
- // }
- // return [
- // 'code' => $code,
- // 'body' => $response ?: '',
- // 'error' => $error_message,
- // 'curl_info' => [
- // 'url' => $url,
- // 'total_time' => $elapsed_time,
- // 'namelookup_time' => 0,
- // 'connect_time' => 0,
- // 'method' => 'file_get_contents (fallback)'
- // ]
- // ];
- }
- /**
- * Fonction helper pour appeler Lucca et gérer les erreurs proprement
- *
- * @param string $method Méthode HTTP
- * @param string $path Chemin de l'endpoint
- * @param array $query Paramètres query string
- * @param mixed $body Corps de la requête
- * @param bool $debug Active le mode debug Lucca
- * @return array Les données décodées (data) en cas de succès
- * @throws Exception En cas d'erreur détaillée
- */
- function lucca_request_safe(string $method, string $path, array $query = [], $body = null, bool $debug = false): array {
- $result = lucca_request($method, $path, $query, $body, 20, $debug);
-
- // Erreur cURL
- if (!empty($result['error'])) {
- throw new Exception("Erreur cURL: " . $result['error']);
- }
-
- // Erreur dans le header X-Lucca-ErrorMessage
- if (!empty($result['lucca_error'])) {
- throw new Exception("Erreur Lucca (header): " . $result['lucca_error']);
- }
-
- // Erreur dans le body ErrorMessage
- if (!empty($result['error_message'])) {
- throw new Exception("Erreur Lucca (body): " . $result['error_message']);
- }
-
- // Code HTTP non-2xx
- if ($result['code'] < 200 || $result['code'] >= 300) {
- $error = "Erreur HTTP {$result['code']}";
-
- // Essayer d'extraire plus d'infos du body
- if (isset($result['data']['title'])) {
- $error .= ": " . $result['data']['title'];
- }
- if (isset($result['data']['traceId'])) {
- $error .= " (traceId: {$result['data']['traceId']})";
- }
-
- throw new Exception($error);
- }
-
- return $result['data'] ?? [];
- }
- /**
- * Formatte une réponse d'erreur détaillée pour les endpoints
- *
- * @param array $result Résultat de lucca_request()
- * @return array Payload d'erreur formaté pour json_response()
- */
- function lucca_format_error(array $result): array {
- $error = [
- "error" => "Erreur API Lucca",
- "http_code" => $result['code'],
- "response_body" => $result['body']
- ];
-
- // ✅ Ajouter X-Lucca-ErrorMessage si présent
- if (!empty($result['lucca_error'])) {
- $error['lucca_error_header'] = $result['lucca_error'];
- }
-
- // ✅ Ajouter ErrorMessage du body si présent
- if (!empty($result['error_message'])) {
- $error['lucca_error_message'] = $result['error_message'];
- }
-
- // ✅ Ajouter les détails du data si disponible
- if (!empty($result['data'])) {
- if (isset($result['data']['title'])) {
- $error['title'] = $result['data']['title'];
- }
- if (isset($result['data']['traceId'])) {
- $error['trace_id'] = $result['data']['traceId'];
- }
- if (isset($result['data']['type'])) {
- $error['type'] = $result['data']['type'];
- }
- }
-
- // Erreur cURL
- if (!empty($result['error'])) {
- $error['curl_error'] = $result['error'];
- }
-
- return $error;
- }
|