Completed
Push — master ( cafb63...ada6f6 )
by Alexandr
17:21 queued 10:27
created

ResolveValidator::hasArrayAccess()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 5.024

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 7
rs 9.2
ccs 3
cts 5
cp 0.6
cc 4
eloc 5
nc 4
nop 1
crap 5.024
1
<?php
2
/**
3
 * Date: 01.12.15
4
 *
5
 * @author Portey Vasil <[email protected]>
6
 */
7
8
namespace Youshido\GraphQL\Validator\ResolveValidator;
9
10
use Youshido\GraphQL\Execution\Context\ExecutionContextInterface;
11
use Youshido\GraphQL\Execution\Request;
12
use Youshido\GraphQL\Field\AbstractField;
13
use Youshido\GraphQL\Field\InputField;
14
use Youshido\GraphQL\Parser\Ast\Argument;
15
use Youshido\GraphQL\Parser\Ast\ArgumentValue\Literal;
16
use Youshido\GraphQL\Parser\Ast\ArgumentValue\Variable;
17
use Youshido\GraphQL\Parser\Ast\Field as AstField;
18
use Youshido\GraphQL\Parser\Ast\Fragment;
19
use Youshido\GraphQL\Parser\Ast\FragmentReference;
20
use Youshido\GraphQL\Parser\Ast\Mutation;
21
use Youshido\GraphQL\Parser\Ast\Query;
22
use Youshido\GraphQL\Type\AbstractType;
23
use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
24
use Youshido\GraphQL\Type\ListType\AbstractListType;
25
use Youshido\GraphQL\Type\Object\AbstractObjectType;
26
use Youshido\GraphQL\Type\TypeMap;
27
use Youshido\GraphQL\Type\TypeService;
28
use Youshido\GraphQL\Type\Union\AbstractUnionType;
29
use Youshido\GraphQL\Validator\Exception\ResolveException;
30
31
class ResolveValidator implements ResolveValidatorInterface
32
{
33
34
    /** @var  ExecutionContextInterface */
35
    protected $executionContext;
36
37 28
    public function __construct(ExecutionContextInterface $executionContext)
38
    {
39 28
        $this->executionContext = $executionContext;
40 28
    }
41
42
    /**
43
     * @param AbstractObjectType      $objectType
44
     * @param Mutation|Query|AstField $field
45
     * @return null
46
     */
47 23
    public function objectHasField($objectType, $field)
48
    {
49 23
        if (!($objectType instanceof AbstractObjectType) || !$objectType->hasField($field->getName())) {
50 3
            $this->executionContext->addError(new ResolveException(sprintf('Field "%s" not found in type "%s"', $field->getName(), $objectType->getNamedType()->getName())));
51
52 3
            return false;
53
        }
54
55 23
        return true;
56
    }
57
58
    /**
59
     * @inheritdoc
60
     */
61 23
    public function validateArguments(AbstractField $field, $query, Request $request)
62
    {
63 23
        if (!count($field->getArguments())) return true;
64
65
        $requiredArguments = array_filter($field->getArguments(), function (InputField $argument) {
66 14
            return $argument->getType()->getKind() == TypeMap::KIND_NON_NULL;
67 14
        });
68
69 14
        $withDefaultArguments = array_filter($field->getArguments(), function (InputField $argument) {
70 14
            return $argument->getConfig()->get('default') !== null;
71 14
        });
72
73 14
        foreach ($query->getArguments() as $argument) {
74 10 View Code Duplication
            if (!$field->hasArgument($argument->getName())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
75 2
                $this->executionContext->addError(new ResolveException(sprintf('Unknown argument "%s" on field "%s"', $argument->getName(), $field->getName())));
76
77 2
                return false;
78
            }
79
80
            /** @var AbstractType $argumentType */
81 10
            $originalArgumentType = $field->getArgument($argument->getName())->getType();
82 10
            $argumentType         = $field->getArgument($argument->getName())->getType()->getNullableType()->getNamedType();
83 10
            if ($argument->getValue() instanceof Variable) {
84
                /** @var Variable $variable */
85 4
                $variable = $argument->getValue();
86
87
                //todo: here validate argument
88
89 4
                if ($variable->getTypeName() !== $argumentType->getName()) {
90 2
                    $this->executionContext->addError(new ResolveException(sprintf('Invalid variable "%s" type, allowed type is "%s"', $variable->getName(), $argumentType->getName())));
91
92 2
                    return false;
93
                }
94
95
                /** @var Variable $requestVariable */
96 3
                $requestVariable = $request->getVariable($variable->getName());
97 3 View Code Duplication
                if (!$requestVariable) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98 1
                    $this->executionContext->addError(new ResolveException(sprintf('Variable "%s" does not exist for query "%s"', $argument->getName(), $field->getName())));
99
100 1
                    return false;
101
                }
102 3
                $variable->setValue($requestVariable);
103
104 3
            }
105
106 9
            $values = $argument->getValue()->getValue();
107 9
            if (!$originalArgumentType instanceof AbstractListType) {
108 9
                $values = [$values];
109 9
            }
110 9
            foreach ($values as $value) {
111 9 View Code Duplication
                if (!$argumentType->isValidValue($argumentType->parseValue($value))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112 1
                    $this->executionContext->addError(new ResolveException(sprintf('Not valid type for argument "%s" in query "%s"', $argument->getName(), $field->getName())));
113
114 1
                    return false;
115
                }
116 9
            }
117
118 9
            if (array_key_exists($argument->getName(), $requiredArguments)) {
119 3
                unset($requiredArguments[$argument->getName()]);
120 3
            }
121 9
            if (array_key_exists($argument->getName(), $withDefaultArguments)) {
122 1
                unset($withDefaultArguments[$argument->getName()]);
123 1
            }
124 13
        }
125
126 13
        if (count($requiredArguments)) {
127 1
            $this->executionContext->addError(new ResolveException(sprintf('Require "%s" arguments to query "%s"', implode(', ', array_keys($requiredArguments)), $query->getName())));
128
129 1
            return false;
130
        }
131
132 12
        if (count($withDefaultArguments)) {
133 1
            foreach ($withDefaultArguments as $name => $argument) {
134 1
                $query->addArgument(new Argument($name, new Literal($argument->getConfig()->get('default'))));
135 1
            }
136 1
        }
137
138 12
        return true;
139
    }
140
141 7
    public function assertTypeImplementsInterface(AbstractType $type, AbstractInterfaceType $interface)
142
    {
143 7
        if (!$interface->isValidValue($type)) {
144 1
            throw new ResolveException('Type ' . $type->getName() . ' does not implement ' . $interface->getName());
145
        }
146 6
    }
147
148 3
    public function assertTypeInUnionTypes(AbstractType $type, AbstractUnionType $unionType)
149
    {
150 3
        $unionTypes = $unionType->getTypes();
151 3
        $valid      = false;
152 3
        if (empty($unionTypes)) return false;
153
154 3
        foreach ($unionTypes as $unionType) {
155 3
            if ($unionType->getName() == $type->getName()) {
156 2
                $valid = true;
157
158 2
                break;
159
            }
160 3
        }
161
162 3
        if (!$valid) {
163 2
            throw new ResolveException('Type ' . $type->getName() . ' not exist in types of ' . $unionType->getName());
164
        }
165 2
    }
166
167
    /**
168
     * @param Fragment          $fragment
169
     * @param FragmentReference $fragmentReference
170
     * @param AbstractType      $queryType
171
     *
172
     * @throws \Exception
173
     */
174 4
    public function assertValidFragmentForField(Fragment $fragment, FragmentReference $fragmentReference, AbstractType $queryType)
175
    {
176 4
        if ($fragment->getModel() !== $queryType->getName()) {
177 1
            throw new ResolveException(sprintf('Fragment reference "%s" not found on model "%s"', $fragmentReference->getName(), $queryType->getName()));
178
        }
179 3
    }
180
181 9
    public function hasArrayAccess($data)
182
    {
183 9
        return is_array($data) ||
184
               ($data instanceof \ArrayAccess &&
185
                $data instanceof \Traversable &&
186 9
                $data instanceof \Countable);
187
    }
188
189 20
    public function isValidValueForField(AbstractField $field, $value)
190
    {
191 20
        $fieldType = $field->getType();
192 20
        if ($fieldType->getKind() == TypeMap::KIND_NON_NULL && is_null($value)) {
193 2
            $this->executionContext->addError(new ResolveException(sprintf('Cannot return null for non-nullable field %s', $field->getName())));
194
195 2
            return null;
196
        } else {
197 20
            $fieldType = $this->resolveTypeIfAbstract($fieldType->getNullableType(), $value);
198
        }
199
200 20 View Code Duplication
        if (!is_null($value) && !$fieldType->isValidValue($value)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201 2
            $this->executionContext->addError(new ResolveException(sprintf('Not valid value for %s field %s', $fieldType->getNullableType()->getKind(), $field->getName())));
202
203 2
            return null;
204
        }
205
206 20
        return true;
207
    }
208
209 20
    public function resolveTypeIfAbstract(AbstractType $type, $resolvedValue)
210
    {
211 20
        if (TypeService::isAbstractType($type)) {
212
            /** @var AbstractInterfaceType $type */
213 6
            $resolvedType = $type->resolveType($resolvedValue);
214
215 6
            if (!$resolvedType) {
216
                $this->executionContext->addError(new \Exception('Cannot resolve type'));
217
218
                return $type;
219
            }
220 6
            if ($type instanceof AbstractInterfaceType) {
221 5
                $this->assertTypeImplementsInterface($resolvedType, $type);
222 5
            } else {
223
                /** @var AbstractUnionType $type */
224 1
                $this->assertTypeInUnionTypes($resolvedType, $type);
225
            }
226
227 6
            return $resolvedType;
228
        }
229
230 20
        return $type;
231
    }
232
233
    /**
234
     * @return ExecutionContextInterface
235
     */
236 2
    public function getExecutionContext()
237
    {
238 2
        return $this->executionContext;
239
    }
240
241
    /**
242
     * @param ExecutionContextInterface $executionContext
243
     */
244
    public function setExecutionContext($executionContext)
245
    {
246
        $this->executionContext = $executionContext;
247
    }
248
249
}
250