Completed
Pull Request — master (#3367)
by Alan
05:13
created

SerializerContextProvider::create()   A

Complexity

Conditions 6
Paths 24

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 24
nop 4
dl 0
loc 26
rs 9.2222
c 0
b 0
f 0
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 ApiPlatform\Core\Serializer\SerializerContextProviderInterface;
19
use GraphQL\Type\Definition\ResolveInfo;
20
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
21
22
/**
23
 * Provides the context used by the Symfony Serializer.
24
 *
25
 * @experimental
26
 *
27
 * @author Alan Poulain <[email protected]>
28
 */
29
final class SerializerContextProvider implements SerializerContextProviderInterface
30
{
31
    private $resourceMetadataFactory;
32
    private $nameConverter;
33
34
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, ?NameConverterInterface $nameConverter)
35
    {
36
        $this->resourceMetadataFactory = $resourceMetadataFactory;
37
        $this->nameConverter = $nameConverter;
38
    }
39
40
    public function create(?string $resourceClass, string $operationName, bool $normalization, array $resolverContext): array
41
    {
42
        $resourceMetadata = $resourceClass ? $this->resourceMetadataFactory->create($resourceClass) : null;
43
44
        $context = [
45
            'resource_class' => $resourceClass,
46
            'graphql_operation_name' => $operationName,
47
        ];
48
49
        if ($normalization) {
50
            $context['attributes'] = $this->fieldsToAttributes($resourceMetadata, $resolverContext);
51
        }
52
53
        if (isset($resolverContext['fields'])) {
54
            $context['no_resolver_data'] = true;
55
        }
56
57
        if ($resourceMetadata) {
58
            $context['input'] = $resourceMetadata->getGraphqlAttribute($operationName, 'input', null, true);
59
            $context['output'] = $resourceMetadata->getGraphqlAttribute($operationName, 'output', null, true);
60
61
            $key = $normalization ? 'normalization_context' : 'denormalization_context';
62
            $context = array_merge($resourceMetadata->getGraphqlAttribute($operationName, $key, [], true), $context);
63
        }
64
65
        return $context;
66
    }
67
68
    /**
69
     * 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).
70
     */
71
    private function fieldsToAttributes(?ResourceMetadata $resourceMetadata, array $context): array
72
    {
73
        if (isset($context['fields'])) {
74
            $fields = $context['fields'];
75
        } else {
76
            /** @var ResolveInfo $info */
77
            $info = $context['info'];
78
            $fields = $info->getFieldSelection(PHP_INT_MAX);
79
        }
80
81
        $attributes = $this->replaceIdKeys($fields['edges']['node'] ?? $fields);
82
83
        if ($context['is_mutation'] || $context['is_subscription']) {
84
            if (!$resourceMetadata) {
85
                throw new \LogicException('ResourceMetadata should always exist for a mutation or a subscription.');
86
            }
87
88
            $wrapFieldName = lcfirst($resourceMetadata->getShortName());
89
90
            return $attributes[$wrapFieldName] ?? [];
91
        }
92
93
        return $attributes;
94
    }
95
96
    private function replaceIdKeys(array $fields): array
97
    {
98
        $denormalizedFields = [];
99
100
        foreach ($fields as $key => $value) {
101
            if ('_id' === $key) {
102
                $denormalizedFields['id'] = $fields['_id'];
103
104
                continue;
105
            }
106
107
            $denormalizedFields[$this->denormalizePropertyName((string) $key)] = \is_array($fields[$key]) ? $this->replaceIdKeys($fields[$key]) : $value;
108
        }
109
110
        return $denormalizedFields;
111
    }
112
113
    private function denormalizePropertyName(string $property): string
114
    {
115
        return null !== $this->nameConverter ? $this->nameConverter->denormalize($property) : $property;
116
    }
117
}
118