Passed
Push — improve-filter-message ( b945de...00229f )
by Han Hui
04:37
created

FieldsToAttributesTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 24
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceIdKeys() 0 12 4
A fieldsToAttributes() 0 5 1
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\Resolver;
15
16
use GraphQL\Type\Definition\ResolveInfo;
17
18
/**
19
 * Transforms the passed GraphQL fields to the list of attributes to serialize.
20
 *
21
 * @author Kévin Dunglas <[email protected]>
22
 */
23
trait FieldsToAttributesTrait
24
{
25
    /**
26
     * 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).
27
     */
28
    private function fieldsToAttributes(ResolveInfo $info): array
29
    {
30
        $fields = $info->getFieldSelection(PHP_INT_MAX);
31
32
        return $this->replaceIdKeys($fields['edges']['node'] ?? $fields);
33
    }
34
35
    private function replaceIdKeys(array $fields): array
36
    {
37
        foreach ($fields as $key => $value) {
38
            if ('_id' === $key) {
39
                $fields['id'] = $fields['_id'];
40
                unset($fields['_id']);
41
            } elseif (\is_array($fields[$key])) {
42
                $fields[$key] = $this->replaceIdKeys($fields[$key]);
43
            }
44
        }
45
46
        return $fields;
47
    }
48
}
49