Completed
Push — master ( 1049ef...ba8cbe )
by Portey
7s
created

ResolveValidator::assertValidFragmentForField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 6
rs 9.4285
ccs 4
cts 4
cp 1
cc 2
eloc 3
nc 2
nop 3
crap 2
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 27
    public function __construct(ExecutionContextInterface $executionContext)
38
    {
39 27
        $this->executionContext = $executionContext;
40 27
    }
41
42
    /**
43
     * @param AbstractObjectType      $objectType
44
     * @param Mutation|Query|AstField $field
45
     * @return null
46
     */
47 22
    public function objectHasField($objectType, $field)
48
    {
49 22
        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 22
        return true;
56
    }
57
58
    /**
59
     * @inheritdoc
60
     */
61 22
    public function validateArguments(AbstractField $field, $query, Request $request)
62
    {
63 22
        if (!count($field->getArguments())) return true;
64
65
        $requiredArguments = array_filter($field->getArguments(), function (InputField $argument) {
66 13
            return $argument->getType()->getKind() == TypeMap::KIND_NON_NULL;
67 13
        });
68
69 13
        $withDefaultArguments = array_filter($field->getArguments(), function (InputField $argument) {
70 13
            return $argument->getConfig()->get('default') !== null;
71 13
        });
72
73 13
        foreach ($query->getArguments() as $argument) {
74 9 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 9
            $originalArgumentType = $field->getArgument($argument->getName())->getType();
82 9
            $argumentType         = $field->getArgument($argument->getName())->getType()->getNullableType()->getNamedType();
83 9
            if ($argument->getValue() instanceof Variable) {
84
                /** @var Variable $variable */
85 3
                $variable = $argument->getValue();
86
87
                //todo: here validate argument
88
89 3
                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 2
                $requestVariable = $request->getVariable($variable->getName());
97 2 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 2
                $variable->setValue($requestVariable);
103
104
            }
105
106 8
            $values = $argument->getValue()->getValue();
107 8
            if (!$originalArgumentType instanceof AbstractListType) {
108 8
                $values = [$values];
109
            }
110 8
            foreach($values as $value) {
111 8 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 8
                    return false;
115
                }
116
            }
117
118 8
            if (array_key_exists($argument->getName(), $requiredArguments)) {
119 2
                unset($requiredArguments[$argument->getName()]);
120
            }
121 8
            if (array_key_exists($argument->getName(), $withDefaultArguments)) {
122 8
                unset($withDefaultArguments[$argument->getName()]);
123
            }
124
        }
125
126 12
        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 11
        if (count($withDefaultArguments)) {
133 1
            foreach ($withDefaultArguments as $name => $argument) {
134 1
                $query->addArgument(new Argument($name, new Literal($argument->getConfig()->get('default'))));
135
            }
136
        }
137
138 11
        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 3
                break;
159
            }
160
        }
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 19
    public function isValidValueForField(AbstractField $field, $value)
182
    {
183 19
        $fieldType = $field->getType();
184 19
        if ($fieldType->getKind() == TypeMap::KIND_NON_NULL && is_null($value)) {
185 2
            $this->executionContext->addError(new ResolveException(sprintf('Cannot return null for non-nullable field %s', $field->getName())));
186 2
            return null;
187
        } else {
188 19
            $fieldType = $this->resolveTypeIfAbstract($fieldType->getNullableType(), $value);
189
        }
190
191 19 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...
192 2
            $this->executionContext->addError(new ResolveException(sprintf('Not valid value for %s field %s', $fieldType->getNullableType()->getKind(), $field->getName())));
193 2
            return null;
194
        }
195 19
        return true;
196
    }
197
198 19
    public function resolveTypeIfAbstract(AbstractType $type, $resolvedValue)
199
    {
200 19
        if (TypeService::isAbstractType($type)) {
201
            /** @var AbstractInterfaceType $type */
202 6
            $resolvedType = $type->resolveType($resolvedValue);
203
204 6
            if (!$resolvedType) {
205
                $this->executionContext->addError(new \Exception('Cannot resolve type'));
206
                return $type;
207
            }
208 6
            if ($type instanceof AbstractInterfaceType) {
209 5
                $this->assertTypeImplementsInterface($resolvedType, $type);
210
            } else {
211
                /** @var AbstractUnionType $type */
212 1
                $this->assertTypeInUnionTypes($resolvedType, $type);
213
            }
214
215 6
            return $resolvedType;
216
        }
217
218 19
        return $type;
219
    }
220
    /**
221
     * @return ExecutionContextInterface
222
     */
223 2
    public function getExecutionContext()
224
    {
225 2
        return $this->executionContext;
226
    }
227
228
    /**
229
     * @param ExecutionContextInterface $executionContext
230
     */
231
    public function setExecutionContext($executionContext)
232
    {
233
        $this->executionContext = $executionContext;
234
    }
235
236
}
237