Passed
Push — master ( d346aa...fd2cec )
by Nicolas
04:54
created

UserNormalizer::supportsNormalization()   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 2
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\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 28
    public function supportsNormalization($data, $format = null)
67
    {
68 28
        return $data instanceof User;
69
    }
70
}
71