Passed
Push — fix_2194 ( 888eea )
by Kévin
02:51
created

FieldsToAttributesTrait::replaceIdKeys()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 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
     * Recursively replaces the key "_id" (the raw id in GraphQL) by "id" (the name of the property expected by the Serializer) and flatten edge and node structures (pagination).
27
     */
28
    private function fieldsToAttributes(ResolveInfo $info): array
29
    {
30
        $fields = $info->getFieldSelection(PHP_INT_MAX);
31
        if (isset($fields['edges']['node'])) {
32
            $fields = $fields['edges']['node'];
33
        }
34
35
        return $this->replaceIdKeys($fields);
36
    }
37
38
    private function replaceIdKeys(array $fields): array
39
    {
40
        foreach ($fields as $key => $value) {
41
            if ('_id' === $key) {
42
                $fields['id'] = $fields['_id'];
43
                unset($fields['_id']);
44
            } elseif (\is_array($fields[$key])) {
45
                $fields[$key] = $this->replaceIdKeys($fields[$key]);
46
            }
47
        }
48
49
        return $fields;
50
    }
51
}
52