Completed
Push — master ( f8b59e...f061a0 )
by Rafael
13:35 queued 07:59
created

ObjectFieldResolver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Resolver;
12
13
use Doctrine\Common\Collections\Collection;
14
use Doctrine\Common\Persistence\Proxy;
15
use GraphQL\Deferred;
16
use GraphQL\Error\Error;
17
use GraphQL\Type\Definition\ResolveInfo;
18
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
19
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21
use Symfony\Component\PropertyAccess\PropertyAccessor;
22
use Ynlo\GraphQLBundle\Definition\FieldDefinition;
23
use Ynlo\GraphQLBundle\Definition\FieldsAwareDefinitionInterface;
24
use Ynlo\GraphQLBundle\Definition\QueryDefinition;
25
use Ynlo\GraphQLBundle\Definition\Registry\Endpoint;
26
use Ynlo\GraphQLBundle\Model\ID;
27
use Ynlo\GraphQLBundle\Model\NodeInterface;
28
use Ynlo\GraphQLBundle\Type\Definition\EndpointAwareInterface;
29
use Ynlo\GraphQLBundle\Type\Definition\EndpointAwareTrait;
30
use Ynlo\GraphQLBundle\Type\Types;
31
32
/**
33
 * Default resolver for all object fields
34
 */
35
class ObjectFieldResolver implements ContainerAwareInterface, EndpointAwareInterface
36
{
37
    use ContainerAwareTrait;
38
    use EndpointAwareTrait;
39
40
    /**
41
     * @var FieldsAwareDefinitionInterface
42
     */
43
    protected $definition;
44
45
    /**
46
     * @var DeferredBuffer
47
     */
48
    protected $deferredBuffer;
49
50
    /**
51
     * @var int
52
     */
53
    private static $concurrentUsages;
54
55
    /**
56
     * ObjectFieldResolver constructor.
57
     *
58
     * @param ContainerInterface             $container
59
     * @param Endpoint                       $endpoint
60
     * @param FieldsAwareDefinitionInterface $definition
61
     */
62 22
    public function __construct(ContainerInterface $container, Endpoint $endpoint, FieldsAwareDefinitionInterface $definition)
63
    {
64 22
        $this->definition = $definition;
65 22
        $this->container = $container;
66 22
        $this->endpoint = $endpoint;
67 22
        $this->deferredBuffer = $container->get(DeferredBuffer::class);
68 22
    }
69
70
    /**
71
     * @param mixed       $root
72
     * @param array       $args
73
     * @param mixed       $context
74
     * @param ResolveInfo $info
75
     *
76
     * @return mixed|null|string
77
     *
78
     * @throws Error
79
     */
80 22
    public function __invoke($root, array $args, $context, ResolveInfo $info)
81
    {
82 22
        $value = null;
83 22
        $fieldDefinition = $this->definition->getField($info->fieldName);
84 22
        $this->verifyConcurrentUsage($fieldDefinition);
85
86
        //when use external resolver or use a object method with arguments
87 22
        if ($fieldDefinition->getResolver() || $fieldDefinition->getArguments()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldDefinition->getResolver() of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
88 19
            $queryDefinition = new QueryDefinition();
89 19
            $queryDefinition->setName($fieldDefinition->getName());
90 19
            $queryDefinition->setType($fieldDefinition->getType());
91 19
            $queryDefinition->setNode($fieldDefinition->getNode());
92 19
            $queryDefinition->setArguments($fieldDefinition->getArguments());
93 19
            $queryDefinition->setList($fieldDefinition->isList());
94 19
            $queryDefinition->setMetas($fieldDefinition->getMetas());
95
96 19
            if (!$fieldDefinition->getResolver()) {
97
                if ($fieldDefinition->getOriginType() === \ReflectionMethod::class) {
98
                    $queryDefinition->setResolver($fieldDefinition->getOriginName());
99
                }
100
            } else {
101 19
                $queryDefinition->setResolver($fieldDefinition->getResolver());
102
            }
103
104 19
            $resolver = new ResolverExecutor($this->container, $this->endpoint, $queryDefinition);
105 19
            $value = $resolver($root, $args, $context, $info);
106
        } else {
107 22
            $accessor = new PropertyAccessor(true);
108 22
            $originName = $fieldDefinition->getOriginName() ?? $fieldDefinition->getName();
109 22
            $value = $accessor->getValue($root, $originName);
110
        }
111
112 22
        if (null !== $value && Types::ID === $fieldDefinition->getType()) {
113
            //ID are formed with base64 representation of the Types and real database ID
114
            //in order to create a unique and global identifier for each resource
115
            //@see https://facebook.github.io/relay/docs/graphql-object-identification.html
116 17
            if ($value instanceof ID) {
117 2
                $value = (string) $value;
118
            } else {
119 16
                $value = (string) new ID($this->definition->getName(), $value);
120
            }
121
        }
122
123 22
        if ($value instanceof Collection) {
124 3
            $value = $value->toArray();
125
        }
126
127 22
        if ($value instanceof Proxy && $value instanceof NodeInterface && !$value->__isInitialized()) {
128 3
            $this->deferredBuffer->add($value);
129
130 3
            return new Deferred(
131 3
                function () use ($value) {
132 3
                    $this->deferredBuffer->loadBuffer();
133
134 3
                    return $this->deferredBuffer->getLoadedEntity($value);
135 3
                }
136
            );
137
        }
138
139 22
        return $value;
140
    }
141
142
    /**
143
     * @param FieldDefinition $definition
144
     *
145
     * @throws Error
146
     */
147 22
    private function verifyConcurrentUsage(FieldDefinition $definition)
148
    {
149 22
        if ($maxConcurrentUsage = $definition->getMaxConcurrentUsage()) {
150 2
            $oid = spl_object_hash($definition);
151 2
            $usages = static::$concurrentUsages[$oid] ?? 1;
0 ignored issues
show
Bug introduced by
Since $concurrentUsages is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $concurrentUsages to at least protected.
Loading history...
152 2
            if ($usages > $maxConcurrentUsage) {
153 1
                if (1 === $maxConcurrentUsage) {
154 1
                    $error = sprintf(
155 1
                        'The field "%s" can be fetched only once per query. This field can`t be used in a list.',
156 1
                        $definition->getName()
157
                    );
158
                } else {
159
                    $error = sprintf(
160
                        'The field "%s" can`t be fetched more than %s times per query.',
161
                        $definition->getName(),
162
                        $maxConcurrentUsage
163
                    );
164
                }
165 1
                throw new Error($error);
166
            }
167 1
            static::$concurrentUsages[$oid] = $usages + 1;
168
        }
169 22
    }
170
}
171