Test Failed
Push — master ( 8af420...1fd71c )
by Nicolas
03:42
created

UserNormalizer::normalize()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 3
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 6
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 Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
7
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
8
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
9
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
10
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
11
12
/**
13
 * UserNormalizer.
14
 */
15
class UserNormalizer implements NormalizerInterface, NormalizerAwareInterface
16
{
17
    use NormalizerAwareTrait;
18
19
    /**
20
     * @var TokenStorageInterface
21
     */
22
    private $tokenStorage;
23
24
    /**
25
     * @var JWTTokenManagerInterface
26
     */
27
    private $jwtManager;
28
29
    /**
30
     * @param TokenStorageInterface    $tokenStorage
31
     * @param JWTTokenManagerInterface $jwtManager
32
     */
33 31
    public function __construct(TokenStorageInterface $tokenStorage, JWTTokenManagerInterface $jwtManager)
34
    {
35 31
        $this->tokenStorage = $tokenStorage;
36 31
        $this->jwtManager = $jwtManager;
37 31
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 22
    public function normalize($object, $format = null, array $context = [])
43
    {
44
        /* @var User $object */
45
46
        $data = [
47 22
            'username' => $object->getUsername(),
48 22
            'image' => $object->getImage() ?: 'https://static.productionready.io/images/smiley-cyrus.jpg',
49 22
            'bio' => $object->getBio(),
50
        ];
51
52 22
        if (isset($context['groups']) && in_array('me', $context['groups'], true)) {
53 5
            $data['email'] = $object->getEmail();
54 5
            $data['token'] = $this->jwtManager->create($object);
55
        } else {
56 17
            $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
57 17
            $data['following'] = $user instanceof User ? $user->follows($object) : false;
58
        }
59
60 22
        return $data;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 24
    public function supportsNormalization($data, $format = null)
67
    {
68 24
        return $data instanceof User;
69
    }
70
}
71