95 lines
2.5 KiB
PHP
95 lines
2.5 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/../vendor/autoload.php';
|
|
|
|
use Monolog\Logger;
|
|
use Monolog\Handler\StreamHandler;
|
|
use FormatConverter\Converter\FormatConverter;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
$logger = new Logger('format_converter');
|
|
$logger->pushHandler(new StreamHandler(__DIR__ . '/../logs/app.log', Logger::DEBUG));
|
|
|
|
$converter = new FormatConverter($logger);
|
|
|
|
// Forwardeo al frontend
|
|
if ($_SERVER['REQUEST_URI'] === '/') {
|
|
header('Location: /index.html');
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Maneja la conversión de formatos.
|
|
*/
|
|
function handleConversion(FormatConverter $converter)
|
|
{
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
sendErrorResponse(405, 'Método no permitido.');
|
|
return;
|
|
}
|
|
|
|
$inputData = file_get_contents('php://input');
|
|
$requestData = json_decode($inputData, true);
|
|
|
|
// Validar datos de entrada
|
|
if (json_last_error() !== JSON_ERROR_NONE || empty($requestData['inputData']) || empty($requestData['inputFormat']) || empty($requestData['outputFormat'])) {
|
|
sendErrorResponse(400, 'Solicitud no es válida. Asegúrese de que los datos están correctamente formateados.');
|
|
return;
|
|
}
|
|
|
|
$inputData = $requestData['inputData'];
|
|
$inputFormat = $requestData['inputFormat'];
|
|
$outputFormat = $requestData['outputFormat'];
|
|
|
|
if ($inputFormat === $outputFormat) {
|
|
sendErrorResponse(400, 'Los formatos de entrada y salida no pueden ser iguales.');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$convertedData = $converter->convert($inputFormat, $outputFormat, $inputData);
|
|
|
|
if ($convertedData === null) {
|
|
sendErrorResponse(500, 'Error interno en el servidor.');
|
|
} else {
|
|
sendSuccessResponse(['convertedData' => $convertedData]);
|
|
}
|
|
} catch (Exception $e) {
|
|
sendErrorResponse(500, 'Error en la conversión: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Envía una respuesta JSON con éxito.
|
|
*
|
|
* @param array $data
|
|
*/
|
|
function sendSuccessResponse(array $data)
|
|
{
|
|
header('Content-Type: application/json');
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'data' => $data
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Envía una respuesta JSON de error.
|
|
*
|
|
* @param int $statusCode
|
|
* @param string $message
|
|
*/
|
|
function sendErrorResponse(int $statusCode, string $message)
|
|
{
|
|
http_response_code($statusCode);
|
|
header('Content-Type: application/json');
|
|
echo json_encode([
|
|
'status' => 'error',
|
|
'message' => $message
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
handleConversion($converter);
|