1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Component Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentBundle\Serializer\Normalizer; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Api\ResourceClassResolverInterface; |
17
|
|
|
use ApiPlatform\Core\Util\ClassInfoTrait; |
18
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
19
|
|
|
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface; |
20
|
|
|
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface; |
21
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; |
22
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; |
23
|
|
|
use Traversable; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @author Daniel West <[email protected]> |
27
|
|
|
*/ |
28
|
|
|
class PersistedNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface |
29
|
|
|
{ |
30
|
|
|
use NormalizerAwareTrait; |
31
|
|
|
use ClassInfoTrait; |
32
|
|
|
|
33
|
|
|
private const ALREADY_CALLED = 'PERSISTED_NORMALIZER_ALREADY_CALLED'; |
34
|
|
|
|
35
|
|
|
private EntityManagerInterface $entityManager; |
36
|
|
|
private ResourceClassResolverInterface $resourceClassResolver; |
37
|
|
|
|
38
|
6 |
|
public function __construct( |
39
|
|
|
EntityManagerInterface $entityManager, |
40
|
|
|
ResourceClassResolverInterface $resourceClassResolver |
41
|
|
|
) { |
42
|
6 |
|
$this->entityManager = $entityManager; |
43
|
6 |
|
$this->resourceClassResolver = $resourceClassResolver; |
44
|
6 |
|
} |
45
|
|
|
|
46
|
2 |
|
public function normalize($object, $format = null, array $context = []) |
47
|
|
|
{ |
48
|
2 |
|
$context[self::ALREADY_CALLED] = true; |
49
|
2 |
|
$context[MetadataNormalizer::METADATA_CONTEXT]['persisted'] = $this->entityManager->contains($object); |
50
|
|
|
|
51
|
2 |
|
return $this->normalizer->normalize($object, $format, $context); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
public function supportsNormalization($data, $format = null, $context = []): bool |
55
|
|
|
{ |
56
|
3 |
|
if (isset($context[self::ALREADY_CALLED])) { |
57
|
1 |
|
return false; |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
if (!\is_object($data) || $data instanceof Traversable) { |
61
|
1 |
|
return false; |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
return $this->resourceClassResolver->isResourceClass($this->getObjectClass($data)); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
public function hasCacheableSupportsMethod(): bool |
68
|
|
|
{ |
69
|
1 |
|
return false; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|