src/Car/Serializer/Normalizer/CarNormalizer.php line 41

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * Copyright (c) 2023 TECLA Consulting Group oü.
  5.  * All rights reserved.
  6.  *
  7.  * This unpublished material is proprietary to TECLA Consulting Group oü.
  8.  * All rights reserved. The methods and
  9.  * techniques described herein are considered trade secrets
  10.  * and/or confidential. Reproduction or distribution, in whole
  11.  * or in part, is forbidden except by express written permission
  12.  * of TECLA Consulting Group oü.
  13.  *
  14.  * @author    Matúš Sýkorjak <matus@tecla.no>
  15.  * @copyright 2023 TECLA Consulting Group oü
  16.  */
  17. namespace App\Car\Serializer\Normalizer;
  18. use App\Car\Model\CarInterface;
  19. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  20. use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
  21. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  22. use Twig\Environment;
  23. final class CarNormalizer implements NormalizerInterfaceCacheableSupportsMethodInterface
  24. {
  25.     private NormalizerInterface $normalizer;
  26.     private Environment $twig;
  27.     public function __construct(
  28.         NormalizerInterface $normalizer,
  29.         Environment $twig
  30.     ) {
  31.         $this->normalizer $normalizer;
  32.         $this->twig $twig;
  33.     }
  34.     public function normalize(mixed $objectstring $format null, array $context = []): array|string|int|float|bool|\ArrayObject|null
  35.     {
  36.         $data $this->normalizer->normalize($object$format$context);
  37.         $data $this->normalizeHtml($object$context$data);
  38.         return $data;
  39.     }
  40.     public function supportsNormalization(mixed $data, ?string $format null, array $context = []): bool
  41.     {
  42.         return $data instanceof CarInterface;
  43.     }
  44.     public function hasCacheableSupportsMethod(): bool
  45.     {
  46.         return __CLASS__ === self::class;
  47.     }
  48.     private function getGroups(array $context): array
  49.     {
  50.         $groups $context[AbstractNormalizer::GROUPS] ?? [];
  51.         return \is_scalar($groups) ? (array) $groups $groups;
  52.     }
  53.     private function normalizeHtml(CarInterface $car, array $context, array $data): array
  54.     {
  55.         $groups $this->getGroups($context);
  56.         if (!\in_array('car.list'$groups)) {
  57.             return $data;
  58.         }
  59.         $html $this->twig->load('packages/car/fragment/_car_list_row.html.twig');
  60.         $data['_html'] = $html->render(['car' => $car]);
  61.         return $data;
  62.     }
  63. }