Completed
Pull Request — master (#1602)
by Kévin
04:13
created

ResourceFieldResolver   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 1
dl 0
loc 27
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 17 9
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 ApiPlatform\Core\Api\IriConverterInterface;
17
use ApiPlatform\Core\GraphQl\Serializer\ItemNormalizer;
18
use GraphQL\Type\Definition\ResolveInfo;
19
20
/**
21
 * A field resolver that resolves IDs to IRIs and allow to access to the raw ID using the "#id" field.
22
 *
23
 * @experimental
24
 *
25
 * @author Kévin Dunglas <[email protected]>
26
 */
27
final class ResourceFieldResolver
28
{
29
    private $iriConverter;
30
31
    public function __construct(IriConverterInterface $iriConverter)
32
    {
33
        $this->iriConverter = $iriConverter;
34
    }
35
36
    public function __invoke($source, $args, $context, ResolveInfo $info)
37
    {
38
        $property = null;
39
        if ('id' === $info->fieldName && isset($source[ItemNormalizer::ITEM_KEY])) {
40
            return $this->iriConverter->getIriFromItem(unserialize($source[ItemNormalizer::ITEM_KEY]));
41
        }
42
43
        if ('_id' === $info->fieldName && isset($source['id'])) {
44
            $property = $source['id'];
45
        } elseif (\is_array($source) && isset($source[$info->fieldName])) {
46
            $property = $source[$info->fieldName];
47
        } elseif (isset($source->{$info->fieldName})) {
48
            $property = $source->{$info->fieldName};
49
        }
50
51
        return $property instanceof \Closure ? $property($source, $args, $context) : $property;
52
    }
53
}
54