UserNormalizer   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 22
c 3
b 0
f 1
dl 0
loc 53
ccs 19
cts 19
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hasCacheableSupportsMethod() 0 3 1
A normalize() 0 23 5
A __construct() 0 4 1
A supportsNormalization() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Serializer\Normalizer;
6
7
use App\Entity\User;
8
use App\Exception\NoCurrentUserException;
9
use App\Security\UserResolver;
10
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
11
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
12
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
13
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
14
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
15
16
final class UserNormalizer implements NormalizerInterface, NormalizerAwareInterface, CacheableSupportsMethodInterface
17
{
18
    use NormalizerAwareTrait;
19
20
    private UserResolver $userResolver;
21
22
    private JWTTokenManagerInterface $jwtManager;
23
24 37
    public function __construct(UserResolver $userResolver, JWTTokenManagerInterface $jwtManager)
25
    {
26 37
        $this->userResolver = $userResolver;
27 37
        $this->jwtManager = $jwtManager;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 22
    public function normalize($object, string $format = null, array $context = []): array
34
    {
35
        /* @var User $object */
36
37
        $data = [
38 22
            'username' => $object->getUsername(),
39 22
            'image' => $object->getImage() ?: 'https://static.productionready.io/images/smiley-cyrus.jpg',
40 22
            'bio' => $object->getBio(),
41
        ];
42
43 22
        if (isset($context['groups']) && \in_array('me', $context['groups'], true)) {
44 5
            $data['email'] = $object->getEmail();
45 5
            $data['token'] = $this->jwtManager->create($object);
46
        } else {
47
            try {
48 17
                $user = $this->userResolver->getCurrentUser();
49 10
                $data['following'] = $user->follows($object);
50 7
            } catch (NoCurrentUserException $exception) {
51 7
                $data['following'] = false;
52
            }
53
        }
54
55 22
        return $data;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 34
    public function supportsNormalization($data, string $format = null): bool
62
    {
63 34
        return $data instanceof User;
64
    }
65
66 34
    public function hasCacheableSupportsMethod(): bool
67
    {
68 34
        return true;
69
    }
70
}
71