UserNormalizer::normalize()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 5
eloc 14
c 2
b 0
f 1
nc 4
nop 3
dl 0
loc 23
ccs 12
cts 12
cp 1
crap 5
rs 9.4888
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