Completed
Pull Request — master (#1585)
by Kévin
03:07
created

ItemResolver   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 5
dl 0
loc 38
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B __invoke() 0 22 4
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\Exception\ItemNotFoundException;
18
use ApiPlatform\Core\Graphql\Serializer\ItemNormalizer;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
20
use ApiPlatform\Core\Util\ClassInfoTrait;
21
use GraphQL\Type\Definition\ResolveInfo;
22
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
23
24
/**
25
 * Creates a function retrieving an item to resolve a GraphQL query.
26
 *
27
 * @experimental
28
 *
29
 * @author Alan Poulain <[email protected]>
30
 * @author Kévin Dunglas <[email protected]>
31
 */
32
final class ItemResolver
33
{
34
    use ClassInfoTrait;
35
36
    private $iriConverter;
37
    private $normalizer;
38
    private $resourceMetadataFactory;
39
40
    public function __construct(IriConverterInterface $iriConverter, NormalizerInterface $normalizer, ResourceMetadataFactoryInterface $resourceMetadataFactory)
41
    {
42
        $this->iriConverter = $iriConverter;
43
        $this->normalizer = $normalizer;
44
        $this->resourceMetadataFactory = $resourceMetadataFactory;
45
    }
46
47
    public function __invoke($source, $args, $context, ResolveInfo $info)
48
    {
49
        // Data already fetched and normalized (field or nested resource)
50
        if (isset($source[$info->fieldName])) {
51
            return $source[$info->fieldName];
52
        }
53
54
        if (!isset($args['id'])) {
55
            return null;
56
        }
57
58
        // TODO: initialize the EagerLoading extension
59
        try {
60
            $item = $this->iriConverter->getItemFromIri($args['id']);
61
        } catch (ItemNotFoundException $e) {
62
            return null;
63
        }
64
65
        $normalizationContext = $this->resourceMetadataFactory->create($this->getObjectClass($item))->getGraphqlAttribute('query', 'normalization_context', [], true);
66
67
        return $this->normalizer->normalize($item, ItemNormalizer::FORMAT, $normalizationContext + ['attributes' => $info->getFieldSelection(PHP_INT_MAX)]);
68
    }
69
}
70