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

UserNormalizer::normalize()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 3
dl 0
loc 19
ccs 9
cts 9
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace App\Serializer\Normalizer;
4
5
use App\Entity\User;
6
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
7
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
8
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
9
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
10
11
/**
12
 * UserNormalizer.
13
 */
14
class UserNormalizer implements NormalizerInterface, NormalizerAwareInterface
15
{
16
    use NormalizerAwareTrait;
17
18
    /**
19
     * @var TokenStorageInterface
20
     */
21
    private $tokenStorage;
22
23
    /**
24
     * @param TokenStorageInterface $tokenStorage
25
     */
26 19
    public function __construct(TokenStorageInterface $tokenStorage)
27
    {
28 19
        $this->tokenStorage = $tokenStorage;
29 19
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 16
    public function normalize($object, $format = null, array $context = [])
35
    {
36
        /* @var User $object */
37
38
        $data = [
39 16
            'username' => $object->getUsername(),
40 16
            'image' => $object->getImage(),
41 16
            'bio' => $object->getBio(),
42
        ];
43
44 16
        if (isset($context['groups']) && in_array('me', $context['groups'], true)) {
45 4
            $data['email'] = $object->getEmail();
46
        } else {
47
            /** @var User $user */
48 12
            $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
49 12
            $data['following'] = $user instanceof User ? $user->follows($object) : false;
0 ignored issues
show
introduced by
$user is always a sub-type of App\Entity\User.
Loading history...
50
        }
51
52 16
        return $data;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 16
    public function supportsNormalization($data, $format = null)
59
    {
60 16
        return $data instanceof User;
61
    }
62
}
63