2021-12-21 10:59:23 +01:00

75 lines
2.2 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Repository\CenterRepository;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function array_key_exists;
class CenterNormalizer implements DenormalizerInterface, NormalizerInterface
{
private CenterRepository $repository;
public function __construct(CenterRepository $repository)
{
$this->repository = $repository;
}
public function denormalize($data, string $type, ?string $format = null, array $context = [])
{
if (false === array_key_exists('type', $data)) {
throw new InvalidArgumentException('missing "type" key in data');
}
if ('center' !== $data['type']) {
throw new InvalidArgumentException('type should be equal to "center"');
}
if (false === array_key_exists('id', $data)) {
throw new InvalidArgumentException('missing "id" key in data');
}
$center = $this->repository->find($data['id']);
if (null === $center) {
throw new UnexpectedValueException("The type with id {$data['id']} does not exists");
}
return $center;
}
public function normalize($center, ?string $format = null, array $context = [])
{
/** @var Center $center */
return [
'id' => $center->getId(),
'type' => 'center',
'name' => $center->getName(),
];
}
public function supportsDenormalization($data, string $type, ?string $format = null)
{
return Center::class === $type;
}
public function supportsNormalization($data, ?string $format = null): bool
{
return $data instanceof Center && 'json' === $format;
}
}