Serial2Format/src/Converter/FormatConverter.php

46 lines
1.5 KiB
PHP

<?php
namespace FormatConverter\Converter;
use FormatConverter\Interfaces\FormatAdapterInterface;
use FormatConverter\Adapters\JsonAdapter;
use FormatConverter\Adapters\XmlAdapter;
use FormatConverter\Adapters\PhpSerializedAdapter;
use Psr\Log\LoggerInterface;
class FormatConverter
{
private array $adapters = [];
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
$this->adapters = [
'json' => new JsonAdapter(),
'xml' => new XmlAdapter(),
'phpSerialized' => new PhpSerializedAdapter()
];
}
public function convert(string $inputFormat, string $outputFormat, string $data): ?string
{
try {
if (!isset($this->adapters[$inputFormat]) || !isset($this->adapters[$outputFormat])) {
throw new \InvalidArgumentException("Formatos no soportados.");
}
/** @var FormatAdapterInterface $inputAdapter */
$inputAdapter = $this->adapters[$inputFormat];
/** @var FormatAdapterInterface $outputAdapter */
$outputAdapter = $this->adapters[$outputFormat];
$transformedData = $inputAdapter->deserialize($data);
return $outputAdapter->serialize($transformedData);
} catch (\Exception $e) {
$this->logger->error('Error en la conversion de formatos' , ['exception' => $e]);
return null;
}
}
}