mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-29 05:26:13 +00:00
80 lines
2.2 KiB
PHP
80 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/*
|
|
* 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.
|
|
*/
|
|
|
|
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, $type, $format = null, array $context = [])
|
|
{
|
|
if (null === $data) {
|
|
return null;
|
|
}
|
|
|
|
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, $format = null, array $context = [])
|
|
{
|
|
/** @var Center $center */
|
|
return [
|
|
'id' => $center->getId(),
|
|
'type' => 'center',
|
|
'name' => $center->getName(),
|
|
'isActive' => $center->getIsActive()
|
|
];
|
|
}
|
|
|
|
public function supportsDenormalization($data, $type, $format = null)
|
|
{
|
|
return Center::class === $type;
|
|
}
|
|
|
|
public function supportsNormalization($data, $format = null): bool
|
|
{
|
|
return $data instanceof Center && 'json' === $format;
|
|
}
|
|
}
|