Passed
Branch develop (7f369c)
by Nicolas
04:17
created

ArticleNormalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 18
    public function __construct(TokenStorageInterface $tokenStorage)
29
    {
30 18
        $this->tokenStorage = $tokenStorage;
31 18
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 7
    public function normalize($object, $format = null, array $context = [])
37
    {
38
        /* @var Article $object */
39
40
        $data = [
41 7
            'slug' => $object->getSlug(),
42 7
            'title' => $object->getTitle(),
43 7
            'description' => $object->getDescription(),
44 7
            'body' => $object->getBody(),
45 7
            'tagList' => array_map(function (Tag $tag) {
46 6
                return $this->normalizer->normalize($tag);
47 7
            }, $object->getTags()->toArray()),
48 7
            'createdAt' => $this->normalizer->normalize($object->getCreatedAt()),
49 7
            'updatedAt' => $this->normalizer->normalize($object->getCreatedAt()),
50
            'favorited' => false,
51 7
            'favoritesCount' => $object->getFavoritedByCount(),
52 7
            'author' => $this->normalizer->normalize($object->getAuthor()),
53
        ];
54
55 7
        $token = $this->tokenStorage->getToken();
56 7
        $user = $token ? $token->getUser() : null;
57
58 7
        if ($user instanceof User) {
59 7
            $data['favorited'] = $user->hasFavorite($object);
60
        }
61
62 7
        return $data;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 16
    public function supportsNormalization($data, $format = null)
69
    {
70 16
        return $data instanceof Article;
71
    }
72
}
73