Passed
Pull Request — feature/publishable (#43)
by Vincent
22:11 queued 16:10
created

PublishableNormalizer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 16
c 1
b 0
f 0
dl 0
loc 42
ccs 0
cts 17
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A supportsNormalization() 0 11 4
A normalize() 0 11 2
A hasCacheableSupportsMethod() 0 3 1
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
        // todo isPublished or is_published?
46
        if (!\array_key_exists('isPublished', $data)) {
47
            $data['isPublished'] = $this->publishableHelper->isPublished($object);
48
        }
49
50
        return $data;
51
    }
52
53
    public function supportsNormalization($data, $format = null, $context = []): bool
54
    {
55
        if (isset($context[self::ALREADY_CALLED])) {
56
            return false;
57
        }
58
59
        if (!\is_object($data) || $data instanceof \Traversable) {
60
            return false;
61
        }
62
63
        return $this->publishableHelper->isPublishable($data);
64
    }
65
66
    public function hasCacheableSupportsMethod(): bool
67
    {
68
        return false;
69
    }
70
}
71