ArticleNormalizer::normalize()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 16
c 1
b 0
f 1
nc 4
nop 3
dl 0
loc 25
ccs 15
cts 15
cp 1
crap 3
rs 9.7333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Serializer\Normalizer;
6
7
use App\Entity\Article;
8
use App\Entity\Tag;
9
use App\Entity\User;
10
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
11
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
12
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
13
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
14
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
15
16
final class ArticleNormalizer implements NormalizerInterface, NormalizerAwareInterface, CacheableSupportsMethodInterface
17
{
18
    use NormalizerAwareTrait;
19
20
    private TokenStorageInterface $tokenStorage;
21
22 36
    public function __construct(TokenStorageInterface $tokenStorage)
23
    {
24 36
        $this->tokenStorage = $tokenStorage;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30 12
    public function normalize($object, string $format = null, array $context = []): array
31
    {
32
        /* @var Article $object */
33
34
        $data = [
35 12
            'slug' => $object->getSlug(),
36 12
            'title' => $object->getTitle(),
37 12
            'description' => $object->getDescription(),
38 12
            'body' => $object->getBody(),
39 12
            'tagList' => array_map(fn (Tag $tag) => $this->normalizer->normalize($tag), $object->getTags()->toArray()),
40 12
            'createdAt' => $this->normalizer->normalize($object->getCreatedAt()),
41 12
            'updatedAt' => $this->normalizer->normalize($object->getCreatedAt()),
42
            'favorited' => false,
43 12
            'favoritesCount' => $object->getFavoritedByCount(),
44 12
            'author' => $this->normalizer->normalize($object->getAuthor()),
45
        ];
46
47 12
        $token = $this->tokenStorage->getToken();
48 12
        $user = $token !== null ? $token->getUser() : null;
49
50 12
        if ($user instanceof User) {
51 6
            $data['favorited'] = $user->hasFavorite($object);
52
        }
53
54 12
        return $data;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 34
    public function supportsNormalization($data, string $format = null): bool
61
    {
62 34
        return $data instanceof Article;
63
    }
64
65 34
    public function hasCacheableSupportsMethod(): bool
66
    {
67 34
        return true;
68
    }
69
}
70