refactor solution to PHP through AI
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
require_once __DIR__ . '/../common/HttpClient.php';
|
||||
|
||||
use ElixForms\Common\HttpClient;
|
||||
|
||||
try {
|
||||
// 1. Lettura dei parametri di input
|
||||
$term = $_GET['term'] ?? '';
|
||||
$codFis = $_GET['cod_fis'] ?? '';
|
||||
|
||||
if (empty($term) || strlen($term) < 3) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'Il parametro di ricerca "term" deve contenere almeno 3 caratteri.'], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (empty($codFis)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'Il parametro "cod_fis" (Codice Fiscale) è obbligatorio.'], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
// 2. Caricamento configurazione
|
||||
$configFile = __DIR__ . '/config.json';
|
||||
if (!file_exists($configFile)) {
|
||||
throw new \RuntimeException('File di configurazione config.json non trovato.');
|
||||
}
|
||||
|
||||
$configJson = file_get_contents($configFile);
|
||||
$config = json_decode($configJson, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || !isset($config['contrattiWS'])) {
|
||||
throw new \RuntimeException('Configurazione del Web Service "contrattiWS" mancante o non valida.');
|
||||
}
|
||||
|
||||
$wsConfig = $config['contrattiWS'];
|
||||
$apiUrl = $wsConfig['apiUrl'] ?? '';
|
||||
$apiUsername = $wsConfig['apiUsername'] ?? '';
|
||||
$apiPassword = $wsConfig['apiPassword'] ?? '';
|
||||
$apiKey = $wsConfig['apiKey'] ?? '';
|
||||
|
||||
// 3. Inizializzazione ed esecuzione della chiamata HTTP con HttpClient
|
||||
$client = new HttpClient([
|
||||
'X-Api-Key' => $apiKey,
|
||||
'Accept' => 'application/json'
|
||||
]);
|
||||
|
||||
// Configura autenticazione basic
|
||||
$client->setBasicAuth($apiUsername, $apiPassword);
|
||||
|
||||
// Esegui la richiesta GET
|
||||
$responseBody = $client->get($apiUrl, [
|
||||
'cod_fis' => $codFis,
|
||||
'term' => $term
|
||||
]);
|
||||
|
||||
// Valida che la risposta sia in formato JSON corretto
|
||||
json_decode($responseBody);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new \RuntimeException('Il servizio contratti ha restituito una risposta in un formato non valido (non JSON).');
|
||||
}
|
||||
|
||||
// Ritorna la risposta del WS direttamente
|
||||
echo $responseBody;
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'error' => 'Errore durante la ricerca dei contratti.',
|
||||
'message' => 'Servizio temporaneamente non disponibile o risposta non valida.'
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
Reference in New Issue
Block a user