Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#23)
by Jérémiah
12:05
created

QueryComplexity::getRawVariableValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the OverblogGraphQLBundle package.
5
 *
6
 * (c) Overblog <http://github.com/overblog/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Overblog\GraphQLBundle\Request\Validator\Rule;
13
14
use GraphQL\Error;
15
use GraphQL\Executor\Values;
16
use GraphQL\Language\AST\Field;
17
use GraphQL\Language\AST\FragmentSpread;
18
use GraphQL\Language\AST\Node;
19
use GraphQL\Language\AST\OperationDefinition;
20
use GraphQL\Language\AST\SelectionSet;
21
use GraphQL\Language\Visitor;
22
use GraphQL\Type\Definition\FieldDefinition;
23
use GraphQL\Validator\ValidationContext;
24
25
class QueryComplexity extends AbstractQuerySecurity
26
{
27
    const DEFAULT_QUERY_MAX_COMPLEXITY = self::DISABLED;
28
29
    private static $maxQueryComplexity;
30
31
    private static $rawVariableValues = [];
32
33
    private $variableDefs;
34
35
    private $fieldAstAndDefs;
36
37
    /**
38
     * @var ValidationContext
39
     */
40
    private $context;
41
42 47
    public function __construct($maxQueryDepth = self::DEFAULT_QUERY_MAX_COMPLEXITY)
43
    {
44 47
        $this->setMaxQueryComplexity($maxQueryDepth);
45 46
    }
46
47 11
    public static function maxQueryComplexityErrorMessage($max, $count)
48
    {
49 11
        return sprintf('Max query complexity should be %d but got %d.', $max, $count);
50
    }
51
52
    /**
53
     * Set max query complexity. If equal to 0 no check is done. Must be greater or equal to 0.
54
     *
55
     * @param $maxQueryComplexity
56
     */
57 47
    public static function setMaxQueryComplexity($maxQueryComplexity)
58
    {
59 47
        self::checkIfGreaterOrEqualToZero('maxQueryComplexity', $maxQueryComplexity);
60
61 46
        self::$maxQueryComplexity = (int) $maxQueryComplexity;
62 46
    }
63
64 46
    public static function getMaxQueryComplexity()
65
    {
66 46
        return self::$maxQueryComplexity;
67
    }
68
69 37
    public static function setRawVariableValues(array $rawVariableValues = null)
70
    {
71 37
        self::$rawVariableValues = $rawVariableValues ?: [];
72 37
    }
73
74 12
    public static function getRawVariableValues()
75
    {
76 12
        return self::$rawVariableValues;
77
    }
78
79 46
    public function __invoke(ValidationContext $context)
80
    {
81 46
        $this->context = $context;
82
83 46
        $this->variableDefs = new \ArrayObject();
84 46
        $this->fieldAstAndDefs = new \ArrayObject();
85 46
        $complexity = 0;
86
87 46
        return $this->invokeIfNeeded(
88 46
            $context,
89
            [
90
                // Visit FragmentDefinition after visiting FragmentSpread
91 46
                'visitSpreadFragments' => true,
92
                Node::SELECTION_SET => function (SelectionSet $selectionSet) use ($context) {
93 12
                    $this->fieldAstAndDefs = $this->collectFieldASTsAndDefs(
94 12
                        $context,
95 12
                        $context->getParentType(),
96 12
                        $selectionSet,
97 12
                        null,
98 12
                        $this->fieldAstAndDefs
99 12
                    );
100 46
                },
101
                Node::VARIABLE_DEFINITION => function ($def) {
102 1
                    $this->variableDefs[] = $def;
103
104 1
                    return Visitor::skipNode();
105 46
                },
106 46
                Node::OPERATION_DEFINITION => [
107 46
                    'leave' => function (OperationDefinition $operationDefinition) use ($context, &$complexity) {
108 12
                        $complexity = $this->fieldComplexity($operationDefinition, $complexity);
109
110 12
                        if ($complexity > $this->getMaxQueryComplexity()) {
111 11
                            return new Error($this->maxQueryComplexityErrorMessage($this->getMaxQueryComplexity(), $complexity));
112
                        }
113 46
                    },
114 46
                ],
115
            ]
116 46
        );
117
    }
118
119 12 View Code Duplication
    private function fieldComplexity(Node $node, $complexity = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
120
    {
121 12
        if (isset($node->selectionSet)) {
122 12
            foreach ($node->selectionSet->selections as $childNode) {
0 ignored issues
show
Bug introduced by
The property selectionSet does not seem to exist in GraphQL\Language\AST\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
123 12
                $complexity = $this->nodeComplexity($childNode, $complexity);
124 12
            }
125 12
        }
126
127 12
        return $complexity;
128
    }
129
130 12
    private function nodeComplexity(Node $node, $complexity = 0)
131
    {
132 12
        switch ($node->kind) {
133 12
            case Node::FIELD:
134
                // default values
135 12
                $args = [];
136 12
                $complexityFn = 'Overblog\GraphQLBundle\Definition\FieldDefinition::defaultComplexity';
137
138
                // calculate children complexity if needed
139 12
                $childrenComplexity = 0;
140
141
                // node has children?
142 12
                if (isset($node->selectionSet)) {
143 12
                    $childrenComplexity = $this->fieldComplexity($node);
144 12
                }
145
146 12
                $astFieldInfo = $this->astFieldInfo($node);
0 ignored issues
show
Compatibility introduced by
$node of type object<GraphQL\Language\AST\Node> is not a sub-type of object<GraphQL\Language\AST\Field>. It seems like you assume a child class of the class GraphQL\Language\AST\Node to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
147 12
                $fieldDef = $astFieldInfo[1];
148
149 12
                if ($fieldDef instanceof FieldDefinition) {
150 12
                    $args = $this->buildFieldArguments($node);
0 ignored issues
show
Compatibility introduced by
$node of type object<GraphQL\Language\AST\Node> is not a sub-type of object<GraphQL\Language\AST\Field>. It seems like you assume a child class of the class GraphQL\Language\AST\Node to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
151
                    //get complexity fn using fieldDef complexity
152 12
                    if (method_exists($fieldDef, 'getComplexityFn')) {
153 10
                        $complexityFn = $fieldDef->getComplexityFn();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class GraphQL\Type\Definition\FieldDefinition as the method getComplexityFn() does only exist in the following sub-classes of GraphQL\Type\Definition\FieldDefinition: Overblog\GraphQLBundle\Definition\FieldDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
154 10
                    }
155 12
                }
156
157 12
                $complexity += call_user_func_array($complexityFn, [$childrenComplexity, $args]);
158 12
                break;
159
160 3
            case Node::INLINE_FRAGMENT:
161
                // node has children?
162 1
                if (isset($node->selectionSet)) {
163 1
                    $complexity = $this->fieldComplexity($node, $complexity);
164 1
                }
165 1
                break;
166
167 2
            case Node::FRAGMENT_SPREAD:
168 2
                $fragment = $this->getFragment($node);
0 ignored issues
show
Compatibility introduced by
$node of type object<GraphQL\Language\AST\Node> is not a sub-type of object<GraphQL\Language\AST\FragmentSpread>. It seems like you assume a child class of the class GraphQL\Language\AST\Node to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
169
170 2
                if (null !== $fragment) {
171 2
                    $complexity = $this->fieldComplexity($fragment, $complexity);
172 2
                }
173 2
                break;
174 12
        }
175
176 12
        return $complexity;
177
    }
178
179 12
    private function astFieldInfo(Field $field)
180
    {
181 12
        $fieldName = $this->getFieldName($field);
182 12
        $astFieldInfo = [null, null];
183 12
        if (isset($this->fieldAstAndDefs[$fieldName])) {
184 12
            foreach ($this->fieldAstAndDefs[$fieldName] as $astAndDef) {
185 12
                if ($astAndDef[0] == $field) {
186 12
                    $astFieldInfo = $astAndDef;
187 12
                    break;
188
                }
189 12
            }
190 12
        }
191
192 12
        return $astFieldInfo;
193
    }
194
195 12
    private function buildFieldArguments(Field $node)
196
    {
197 12
        $rawVariableValues = $this->getRawVariableValues();
198 12
        $astFieldInfo = $this->astFieldInfo($node);
199 12
        $fieldDef = $astFieldInfo[1];
200
201 12
        $args = [];
202
203 12
        if ($fieldDef instanceof FieldDefinition) {
204 12
            $variableValues = Values::getVariableValues(
205 12
                $this->context->getSchema(),
206 12
                $this->variableDefs,
0 ignored issues
show
Documentation introduced by
$this->variableDefs is of type object<ArrayObject>, but the function expects a array<integer,object<Gra...ST\VariableDefinition>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
207
                $rawVariableValues
208 12
            );
209 12
            $args = Values::getArgumentValues($fieldDef->args, $node->arguments, $variableValues);
0 ignored issues
show
Bug introduced by
It seems like $node->arguments can also be of type null; however, GraphQL\Executor\Values::getArgumentValues() does only seem to accept array<integer,object<Gra...Language\AST\Argument>>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
210 12
        }
211
212 12
        return $args;
213
    }
214
215 46
    protected function isEnabled()
216
    {
217 46
        return $this->getMaxQueryComplexity() !== static::DISABLED;
218
    }
219
}
220