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; |
15
|
|
|
|
16
|
|
|
use Silverback\ApiComponentBundle\Publishable\PublishableHelper; |
17
|
|
|
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface; |
18
|
|
|
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface; |
19
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; |
20
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Adds `isPublished` property on response, if not set. |
24
|
|
|
* |
25
|
|
|
* @author Vincent Chalamon <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class PublishableNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface |
28
|
|
|
{ |
29
|
|
|
use NormalizerAwareTrait; |
30
|
|
|
|
31
|
|
|
private const ALREADY_CALLED = 'PUBLISHABLE_NORMALIZER_ALREADY_CALLED'; |
32
|
|
|
|
33
|
|
|
private PublishableHelper $publishableHelper; |
34
|
|
|
|
35
|
|
|
public function __construct(PublishableHelper $publishableHelper) |
36
|
|
|
{ |
37
|
|
|
$this->publishableHelper = $publishableHelper; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function normalize($object, $format = null, array $context = []) |
41
|
|
|
{ |
42
|
|
|
$context[self::ALREADY_CALLED] = true; |
43
|
|
|
$data = $this->normalizer->normalize($object, $format, $context); |
44
|
|
|
|
45
|
|
|
if (!\array_key_exists('isPublished', $data)) { |
46
|
|
|
$data['isPublished'] = $this->publishableHelper->isPublished($object); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $data; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function supportsNormalization($data, $format = null, $context = []): bool |
53
|
|
|
{ |
54
|
|
|
if (isset($context[self::ALREADY_CALLED])) { |
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (!\is_object($data) || $data instanceof \Traversable) { |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $this->publishableHelper->isPublishable($data); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function hasCacheableSupportsMethod(): bool |
66
|
|
|
{ |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|