Test Failed
Pull Request — feature/publishable (#31)
by Vincent
06:22
created

PublishableContextBuilder::createFromRequest()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 8
c 1
b 0
f 1
dl 0
loc 15
rs 9.2222
cc 6
nc 8
nop 3
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 ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
17
use Silverback\ApiComponentBundle\Publishable\PublishableHelper;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
20
21
/**
22
 * @author Vincent Chalamon <[email protected]>
23
 */
24
final class PublishableContextBuilder implements SerializerContextBuilderInterface
25
{
26
    private SerializerContextBuilderInterface $decorated;
27
    private PublishableHelper $publishableHelper;
28
    private ClassMetadataFactoryInterface $classMetadataFactory;
29
30
    public function __construct(SerializerContextBuilderInterface $decorated, PublishableHelper $publishableHelper, ClassMetadataFactoryInterface $classMetadataFactory)
31
    {
32
        $this->decorated = $decorated;
33
        $this->publishableHelper = $publishableHelper;
34
        $this->classMetadataFactory = $classMetadataFactory;
35
    }
36
37
    public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array
38
    {
39
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
40
41
        $serializerGroupsConfigured = isset($context['groups']) && \is_array($context['groups']);
42
        if (!$serializerGroupsConfigured && $this->classHasSerializerGroupsOnProperties($context['resource_class'])) {
43
            $context['groups'] = [];
44
            $serializerGroupsConfigured = true;
45
        }
46
47
        if ($serializerGroupsConfigured && $this->publishableHelper->isGranted()) {
48
            $context['groups'][] = sprintf('%s:publishable', $context['resource_class']);
49
        }
50
51
        return $context;
52
    }
53
54
    private function classHasSerializerGroupsOnProperties(string $resourceClass): bool
55
    {
56
        $serializerAttributeMetadata = $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata();
57
        foreach ($serializerAttributeMetadata as $metadata) {
58
            if (\count($metadata->groups)) {
59
                return true;
60
            }
61
        }
62
63
        return false;
64
    }
65
}
66