Passed
Push — 2.5 ( 687369...b0939a )
by Alan
03:49
created

denormalizePropertyName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\GraphQl\Serializer;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
18
use GraphQL\Type\Definition\ResolveInfo;
19
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
20
21
/**
22
 * Builds the context used by the Symfony Serializer.
23
 *
24
 * @experimental
25
 *
26
 * @author Alan Poulain <[email protected]>
27
 */
28
final class SerializerContextBuilder implements SerializerContextBuilderInterface
29
{
30
    private $resourceMetadataFactory;
31
    private $nameConverter;
32
33
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, ?NameConverterInterface $nameConverter)
34
    {
35
        $this->resourceMetadataFactory = $resourceMetadataFactory;
36
        $this->nameConverter = $nameConverter;
37
    }
38
39
    public function create(?string $resourceClass, string $operationName, array $resolverContext, bool $normalization): array
40
    {
41
        $resourceMetadata = $resourceClass ? $this->resourceMetadataFactory->create($resourceClass) : null;
42
43
        $context = [
44
            'resource_class' => $resourceClass,
45
            'graphql_operation_name' => $operationName,
46
        ];
47
48
        if ($normalization) {
49
            $context['attributes'] = $this->fieldsToAttributes($resourceMetadata, $resolverContext);
50
        }
51
52
        if ($resourceMetadata) {
53
            $context['input'] = $resourceMetadata->getGraphqlAttribute($operationName, 'input', null, true);
54
            $context['output'] = $resourceMetadata->getGraphqlAttribute($operationName, 'output', null, true);
55
56
            $key = $normalization ? 'normalization_context' : 'denormalization_context';
57
            $context = array_merge($resourceMetadata->getGraphqlAttribute($operationName, $key, [], true), $context);
58
        }
59
60
        return $context;
61
    }
62
63
    /**
64
     * Retrieves fields, recursively replaces the "_id" key (the raw id) by "id" (the name of the property expected by the Serializer) and flattens edge and node structures (pagination).
65
     */
66
    private function fieldsToAttributes(?ResourceMetadata $resourceMetadata, array $context): array
67
    {
68
        /** @var ResolveInfo $info */
69
        $info = $context['info'];
70
        $fields = $info->getFieldSelection(PHP_INT_MAX);
71
72
        $attributes = $this->replaceIdKeys($fields['edges']['node'] ?? $fields);
73
74
        if ($context['is_mutation']) {
75
            if (!$resourceMetadata) {
76
                throw new \LogicException('ResourceMetadata should always exist for a mutation.');
77
            }
78
79
            $wrapFieldName = lcfirst($resourceMetadata->getShortName());
80
81
            return $attributes[$wrapFieldName] ?? [];
82
        }
83
84
        return $attributes;
85
    }
86
87
    private function replaceIdKeys(array $fields): array
88
    {
89
        $denormalizedFields = [];
90
91
        foreach ($fields as $key => $value) {
92
            if ('_id' === $key) {
93
                $denormalizedFields['id'] = $fields['_id'];
94
95
                continue;
96
            }
97
98
            $denormalizedFields[$this->denormalizePropertyName((string) $key)] = \is_array($fields[$key]) ? $this->replaceIdKeys($fields[$key]) : $value;
99
        }
100
101
        return $denormalizedFields;
102
    }
103
104
    private function denormalizePropertyName(string $property): string
105
    {
106
        return null !== $this->nameConverter ? $this->nameConverter->denormalize($property) : $property;
107
    }
108
}
109