Test Failed
Branch develop (7f369c)
by Nicolas
04:26
created

ArticleNormalizer::normalize()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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