Passed
Pull Request — feature/publishable (#43)
by Daniel
05:35
created

PublishableNormalizer::normalize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 10
cc 2
nc 2
nop 3
crap 6
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 `published` 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('published', $data)) {
46
            $data['published'] = $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