|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Serializer\Normalizer; |
| 4 | + |
| 5 | +use ApiPlatform\Core\Api\OperationType; |
| 6 | +use ApiPlatform\Core\Api\UrlGeneratorInterface; |
| 7 | +use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameResolverInterface; |
| 8 | +use App\Entity\ContentType; |
| 9 | +use Symfony\Component\Routing\RouterInterface; |
| 10 | +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
| 11 | +use Symfony\Component\Serializer\SerializerAwareInterface; |
| 12 | +use Symfony\Component\Serializer\SerializerInterface; |
| 13 | + |
| 14 | +/** |
| 15 | + * ... |
| 16 | + */ |
| 17 | +class ContentTypeNormalizer implements NormalizerInterface, SerializerAwareInterface { |
| 18 | + public function __construct( |
| 19 | + private NormalizerInterface $decorated, |
| 20 | + private RouteNameResolverInterface $routeNameResolver, |
| 21 | + private RouterInterface $router, |
| 22 | + ) { |
| 23 | + } |
| 24 | + |
| 25 | + public function supportsNormalization($data, $format = null) { |
| 26 | + return $this->decorated->supportsNormalization($data, $format); |
| 27 | + } |
| 28 | + |
| 29 | + public function normalize($object, $format = null, array $context = []) { |
| 30 | + $data = $this->decorated->normalize($object, $format, $context); |
| 31 | + |
| 32 | + if ($object instanceof ContentType && isset($data['entityClass'])) { |
| 33 | + $data['entityPath'] = $this->router->generate($this->routeNameResolver->getRouteName($data['entityClass'], OperationType::COLLECTION), [], UrlGeneratorInterface::ABS_PATH); |
| 34 | + } |
| 35 | + |
| 36 | + return $data; |
| 37 | + } |
| 38 | + |
| 39 | + public function setSerializer(SerializerInterface $serializer) { |
| 40 | + if ($this->decorated instanceof SerializerAwareInterface) { |
| 41 | + $this->decorated->setSerializer($serializer); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments