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
|
|
|
|