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