handling multi types and acc-period/repositories endpoint

This commit is contained in:
2021-05-13 00:54:32 +02:00
parent 4a04628d5b
commit 87e2ac9386
9 changed files with 434 additions and 6 deletions

View File

@@ -0,0 +1,82 @@
<?php
namespace Chill\PersonBundle\Serializer\Normalizer;
use Chill\PersonBundle\Entity\Person;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\PersonBundle\Entity\AccompanyingPeriod\Resource;
use Chill\PersonBundle\Repository\AccompanyingPeriod\ResourceRepository;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\ObjectToPopulateTrait;
use Symfony\Component\Serializer\Exception;
use Chill\MainBundle\Serializer\Normalizer\DiscriminatedObjectDenormalizer;
class AccompanyingPeriodResourceNormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
use ObjectToPopulateTrait;
public function __construct(ResourceRepository $repository)
{
$this->repository = $repository;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
$resource = $this->extractObjectToPopulate($type, $context);
if ('accompanying_period_resource' !== ($data['type'] ?? NULL)) {
throw new Exception\InvalidArgumentException("the key type must be present in data and set to 'accompanying_period_resource'");
}
if ($resource === NULL && \array_key_exists('id', $data)) {
$resource = $this->repository->find($data['id']);
if (NULL === $resource) {
throw new Exception\UnexpectedValueException(sprintf("the resource with".
"id %d is not found", $data['id']));
}
// if resource found, available only for read-only
if (count($data) > 2) {
unset($data['id']);
unset($data['type']);
throw new Exception\ExtraAttributesException($data);
}
}
if ($resource === NULL) {
$resource = new Resource();
}
if (\array_key_exists('resource', $data)) {
$res = $this->denormalizer->denormalize(
$data['resource'],
DiscriminatedObjectDenormalizer::TYPE,
$format,
\array_merge(
$context,
[
DiscriminatedObjectDenormalizer::ALLOWED_TYPES =>
[
Person::class, ThirdParty::class
]
]
)
);
$resource->setResource($res);
}
return $resource;
}
public function supportsDenormalization($data, string $type, string $format = null)
{
return $type === Resource::class;
}
}