Completed
Push — master ( e9704f...151de8 )
by Portey
04:16
created

ResolveValidator   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 226
Duplicated Lines 7.52 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 95.41%

Importance

Changes 25
Bugs 5 Features 4
Metric Value
wmc 43
c 25
b 5
f 4
lcom 1
cbo 14
dl 17
loc 226
ccs 104
cts 109
cp 0.9541
rs 8.3157

12 Methods

Rating   Name   Duplication   Size   Complexity  
B assertTypeInUnionTypes() 0 18 5
A assertTypeImplementsInterface() 0 6 2
A __construct() 0 4 1
A objectHasField() 0 10 4
C validateArguments() 10 77 14
A assertValidFragmentForField() 0 11 3
A hasArrayAccess() 0 4 2
B isValidValueForField() 7 19 5
A resolveTypeIfAbstract() 0 4 2
A resolveAbstractType() 0 19 3
A getExecutionContext() 0 4 1
A setExecutionContext() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ResolveValidator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ResolveValidator, and based on these observations, apply Extract Interface, too.

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\CompositeTypeInterface;
24
use Youshido\GraphQL\Type\InputObject\AbstractInputObjectType;
25
use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
26
use Youshido\GraphQL\Type\ListType\AbstractListType;
27
use Youshido\GraphQL\Type\Object\AbstractObjectType;
28
use Youshido\GraphQL\Type\TypeMap;
29
use Youshido\GraphQL\Type\TypeService;
30
use Youshido\GraphQL\Type\Union\AbstractUnionType;
31
use Youshido\GraphQL\Validator\Exception\ResolveException;
32
33
class ResolveValidator implements ResolveValidatorInterface
34
{
35
36
    /** @var  ExecutionContextInterface */
37
    protected $executionContext;
38
39 34
    public function __construct(ExecutionContextInterface $executionContext)
40
    {
41 34
        $this->executionContext = $executionContext;
42 34
    }
43
44
    /**
45
     * @param AbstractObjectType      $objectType
46
     * @param Mutation|Query|AstField $field
47
     * @return null
48
     */
49 27
    public function objectHasField($objectType, $field)
50
    {
51 27
        if (!(($objectType instanceof AbstractObjectType || $objectType instanceof AbstractInputObjectType)) || !$objectType->hasField($field->getName())) {
52 2
            $this->executionContext->addError(new ResolveException(sprintf('Field "%s" not found in type "%s"', $field->getName(), $objectType->getNamedType()->getName())));
53
54 2
            return false;
55
        }
56
57 27
        return true;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63 27
    public function validateArguments(AbstractField $field, $query, Request $request)
64
    {
65
        $requiredArguments = array_filter($field->getArguments(), function (InputField $argument) {
66 21
            return $argument->getType()->getKind() == TypeMap::KIND_NON_NULL;
67 27
        });
68
69 27
        $withDefaultArguments = array_filter($field->getArguments(), function (InputField $argument) {
70 21
            return $argument->getConfig()->get('default') !== null;
71 27
        });
72
73 27
        foreach ($query->getArguments() as $argument) {
74 17 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 17
            $originalArgumentType = $field->getArgument($argument->getName())->getType();
82 17
            $argumentType         = $originalArgumentType->getNullableType()->getNamedType();
83 17
            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 16
            $values = $argument->getValue()->getValue();
107 16
            if (!$originalArgumentType instanceof AbstractListType) {
108 15
                $values = [$values];
109 15
            }
110 16
            foreach ($values as $value) {
111 16
                if (!$argumentType->isValidValue($argumentType->parseValue($value))) {
112 3
                    $this->executionContext->addError(new ResolveException(sprintf('Not valid type for argument "%s" in query "%s"', $argument->getName(), $field->getName())));
113
114 3
                    return false;
115
                }
116 16
            }
117
118 15
            if (array_key_exists($argument->getName(), $requiredArguments)) {
119 3
                unset($requiredArguments[$argument->getName()]);
120 3
            }
121 15
            if (array_key_exists($argument->getName(), $withDefaultArguments)) {
122 6
                unset($withDefaultArguments[$argument->getName()]);
123 6
            }
124 25
        }
125
126 25
        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 24
        if (count($withDefaultArguments)) {
133 4
            foreach ($withDefaultArguments as $name => $argument) {
134 4
                $query->addArgument(new Argument($name, new Literal($argument->getConfig()->get('default'))));
135 4
            }
136 4
        }
137
138 24
        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 5
    public function assertValidFragmentForField(Fragment $fragment, FragmentReference $fragmentReference, AbstractType $queryType)
175
    {
176 5
        $innerType = $queryType;
177 5
        while ($innerType->isCompositeType()) {
178 1
            $innerType = $innerType->getTypeOf();
179 1
        }
180
181 5
        if ($fragment->getModel() !== $innerType->getName()) {
182 1
            throw new ResolveException(sprintf('Fragment reference "%s" not found on model "%s"', $fragmentReference->getName(), $queryType->getName()));
183
        }
184 4
    }
185
186 9
    public function hasArrayAccess($data)
187
    {
188 9
        return is_array($data) || $data instanceof \Traversable;
189
    }
190
191 23
    public function isValidValueForField(AbstractField $field, $value)
192
    {
193 23
        $fieldType = $field->getType();
194 23 View Code Duplication
        if ($fieldType->getKind() == TypeMap::KIND_NON_NULL && is_null($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...
195 2
            $this->executionContext->addError(new ResolveException(sprintf('Cannot return null for non-nullable field %s', $field->getName())));
196
197 2
            return null;
198
        } else {
199 23
            $fieldType = $this->resolveTypeIfAbstract($fieldType->getNullableType(), $value);
200
        }
201
202 23
        if (!is_null($value) && !$fieldType->isValidValue($value)) {
203 2
            $this->executionContext->addError(new ResolveException(sprintf('Not valid value for %s field %s', $fieldType->getNullableType()->getKind(), $field->getName())));
204
205 2
            return null;
206
        }
207
208 23
        return true;
209
    }
210
211 23
    public function resolveTypeIfAbstract(AbstractType $type, $resolvedValue)
212
    {
213 23
        return TypeService::isAbstractType($type) ? $this->resolveAbstractType($type, $resolvedValue) : $type;
214
    }
215
216
    /**
217
     * @param AbstractType $type
218
     * @param              $resolvedValue
219
     * @return AbstractObjectType
220
     * @throws ResolveException
221
     */
222 6
    public function resolveAbstractType(AbstractType $type, $resolvedValue)
223
    {
224
        /** @var AbstractInterfaceType $type */
225 6
        $resolvedType = $type->resolveType($resolvedValue);
226
227 6
        if (!$resolvedType) {
228
            $this->executionContext->addError(new \Exception('Cannot resolve type'));
229
230
            return $type;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $type; (Youshido\GraphQL\Type\In...e\AbstractInterfaceType) is incompatible with the return type documented by Youshido\GraphQL\Validat...or::resolveAbstractType of type Youshido\GraphQL\Type\Object\AbstractObjectType.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
231
        }
232 6
        if ($type instanceof AbstractInterfaceType) {
233 5
            $this->assertTypeImplementsInterface($resolvedType, $type);
234 5
        } else {
235
            /** @var AbstractUnionType $type */
236 1
            $this->assertTypeInUnionTypes($resolvedType, $type);
237
        }
238
239 6
        return $resolvedType;
240
    }
241
242
    /**
243
     * @return ExecutionContextInterface
244
     */
245 2
    public function getExecutionContext()
246
    {
247 2
        return $this->executionContext;
248
    }
249
250
    /**
251
     * @param ExecutionContextInterface $executionContext
252
     */
253
    public function setExecutionContext($executionContext)
254
    {
255
        $this->executionContext = $executionContext;
256
    }
257
258
}
259