Completed
Pull Request — master (#6)
by Rafael
09:22
created

ObjectFieldResolver::verifyConcurrentUsage()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 0
cp 0
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 15
nc 4
nop 1
crap 20
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 21
    /**
56
     * ObjectFieldResolver constructor.
57 21
     *
58 21
     * @param ContainerInterface             $container
59 21
     * @param Endpoint                       $endpoint
60 21
     * @param FieldsAwareDefinitionInterface $definition
61 21
     */
62
    public function __construct(ContainerInterface $container, Endpoint $endpoint, FieldsAwareDefinitionInterface $definition)
63
    {
64
        $this->definition = $definition;
65
        $this->container = $container;
66
        $this->endpoint = $endpoint;
67
        $this->deferredBuffer = $container->get(DeferredBuffer::class);
68
    }
69
70
    /**
71 21
     * @param mixed       $root
72
     * @param array       $args
73 21
     * @param mixed       $context
74 21
     * @param ResolveInfo $info
75
     *
76
     * @return mixed|null|string
77 21
     *
78 19
     * @throws Error
79 19
     */
80 19
    public function __invoke($root, array $args, $context, ResolveInfo $info)
81 19
    {
82 19
        $value = null;
83 19
        $fieldDefinition = $this->definition->getField($info->fieldName);
84 19
        $this->verifyConcurrentUsage($fieldDefinition);
85
86 19
        //when use external resolver or use a object method with arguments
87
        if ($fieldDefinition->getResolver() || $fieldDefinition->getArguments()) {
88
            $queryDefinition = new QueryDefinition();
89
            $queryDefinition->setName($fieldDefinition->getName());
90
            $queryDefinition->setType($fieldDefinition->getType());
91 19
            $queryDefinition->setNode($fieldDefinition->getNode());
92
            $queryDefinition->setArguments($fieldDefinition->getArguments());
93
            $queryDefinition->setList($fieldDefinition->isList());
94 19
            $queryDefinition->setMetas($fieldDefinition->getMetas());
95 19
96
            if (!$fieldDefinition->getResolver()) {
97 21
                if ($fieldDefinition->getOriginType() === \ReflectionMethod::class) {
98 21
                    $queryDefinition->setResolver($fieldDefinition->getOriginName());
99 21
                }
100
            } else {
101
                $queryDefinition->setResolver($fieldDefinition->getResolver());
102 21
            }
103
104
            $resolver = new ResolverExecutor($this->container, $this->endpoint, $queryDefinition);
105
            $value = $resolver($root, $args, $context, $info);
106 16
        } else {
107 2
            $accessor = new PropertyAccessor(true);
108
            $originName = $fieldDefinition->getOriginName() ?? $fieldDefinition->getName();
109 15
            $value = $accessor->getValue($root, $originName);
110
        }
111
112
        if (null !== $value && Types::ID === $fieldDefinition->getType()) {
113 21
            //ID are formed with base64 representation of the Types and real database ID
114 3
            //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
            if ($value instanceof ID) {
117 21
                $value = (string) $value;
118 4
            } else {
119
                $value = (string) new ID($this->definition->getName(), $value);
120 4
            }
121 4
        }
122 4
123
        if ($value instanceof Collection) {
124 4
            $value = $value->toArray();
125 4
        }
126
127
        if ($value instanceof Proxy && $value instanceof NodeInterface && !$value->__isInitialized()) {
128
            $this->deferredBuffer->add($value);
129 21
130
            return new Deferred(
131
                function () use ($value) {
132
                    $this->deferredBuffer->loadBuffer();
133
134
                    return $this->deferredBuffer->getLoadedEntity($value);
135
                }
136
            );
137
        }
138
139
        return $value;
140
    }
141
142
    /**
143
     * @param FieldDefinition $definition
144
     *
145
     * @throws Error
146
     */
147
    private function verifyConcurrentUsage(FieldDefinition $definition)
148
    {
149
        if ($maxConcurrentUsage = $definition->getMaxConcurrentUsage()) {
150
            $oid = spl_object_hash($definition);
151
            $usages = static::$concurrentUsages[$oid] ?? 1;
152
            if ($usages > $maxConcurrentUsage) {
153
                if (1 === $maxConcurrentUsage) {
154
                    $error = sprintf(
155
                        'The field "%s" can be fetched only once per query. This field can`t be used in a list.',
156
                        $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
                throw new Error($error);
166
            }
167
            static::$concurrentUsages[$oid] = $usages + 1;
168
        }
169
    }
170
}
171