1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <?php
namespace App\Serializer;
use App\Entity\Category;
use App\Entity\Post;
use App\Entity\UserOwnedInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class UserOwnedDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
private const ALREADY_CALLED_DENORMALIZER = 'UserOwnedDenormalizerCalled';
public function __construct(private Security $security)
{
}
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
$data[self::ALREADY_CALLED_DENORMALIZER] = true;
/** @var UserOwnedInterface $obj */
$obj = $this->denormalizer->denormalize($data, $type, $format, $context);
$obj->setUser($this->security->getUser());
return $obj;
}
public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
{
$reflectionClass = new \ReflectionClass($type);
$alreadyCalled = $data[self::ALREADY_CALLED_DENORMALIZER] ?? false;
return $reflectionClass->implementsInterface(UserOwnedInterface::class) && $alreadyCalled === false;
}
public function getSupportedTypes(?string $format): array
{
return [Post::class => true, Category::class => true];
}
} |
Partager