Passed
Push — master ( bc13b6...650a1b )
by Nicolas
08:26 queued 04:11
created

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