/
BookNormalizer.php
54 lines (45 loc) · 1.61 KB
/
BookNormalizer.php
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
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace App\Serializer;
use App\Entity\Book;
use App\Repository\ReviewRepository;
use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class BookNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @param ReviewRepository $repository
*/
public function __construct(
private RouterInterface $router,
#[Autowire(service: ReviewRepository::class)]
private ObjectRepository $repository
) {
}
/**
* @param Book $object
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
$object->reviews = $this->router->generate('_api_/books/{bookId}/reviews{._format}_get_collection', [
'bookId' => $object->getId(),
]);
$object->rating = $this->repository->getAverageRating($object);
return $this->normalizer->normalize($object, $format, [self::class => true] + $context);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof Book && !isset($context[self::class]);
}
public function getSupportedTypes(?string $format): array
{
return [
Book::class => false,
];
}
}