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
13:51 queued 05:06
created

QueryComplexity::maxQueryComplexityErrorMessage()   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 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
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\InlineFragment;
19
use GraphQL\Language\AST\Node;
20
use GraphQL\Language\AST\OperationDefinition;
21
use GraphQL\Language\AST\SelectionSet;
22
use GraphQL\Language\Visitor;
23
use GraphQL\Type\Definition\FieldDefinition;
24
use GraphQL\Validator\ValidationContext;
25
26
class QueryComplexity extends AbstractQuerySecurity
27
{
28
    const DEFAULT_QUERY_MAX_COMPLEXITY = self::DISABLED;
29
30
    private static $maxQueryComplexity;
31
32
    private static $rawVariableValues = [];
33
34
    private $variableDefs;
35
36
    private $fieldAstAndDefs;
37
38
    /**
39
     * @var ValidationContext
40
     */
41
    private $context;
42
43 47
    public function __construct($maxQueryDepth = self::DEFAULT_QUERY_MAX_COMPLEXITY)
44
    {
45 47
        $this->setMaxQueryComplexity($maxQueryDepth);
46 46
    }
47
48 11
    public static function maxQueryComplexityErrorMessage($max, $count)
49
    {
50 11
        return sprintf('Max query complexity should be %d but got %d.', $max, $count);
51
    }
52
53
    /**
54
     * Set max query complexity. If equal to 0 no check is done. Must be greater or equal to 0.
55
     *
56
     * @param $maxQueryComplexity
57
     */
58 47
    public static function setMaxQueryComplexity($maxQueryComplexity)
59
    {
60 47
        self::checkIfGreaterOrEqualToZero('maxQueryComplexity', $maxQueryComplexity);
61
62 46
        self::$maxQueryComplexity = (int) $maxQueryComplexity;
63 46
    }
64
65 46
    public static function getMaxQueryComplexity()
66
    {
67 46
        return self::$maxQueryComplexity;
68
    }
69
70 37
    public static function setRawVariableValues(array $rawVariableValues = null)
71
    {
72 37
        self::$rawVariableValues = $rawVariableValues ?: [];
73 37
    }
74
75 12
    public static function getRawVariableValues()
76
    {
77 12
        return self::$rawVariableValues;
78
    }
79
80 46
    public function __invoke(ValidationContext $context)
81
    {
82 46
        $this->context = $context;
83
84 46
        $this->variableDefs = new \ArrayObject();
85 46
        $this->fieldAstAndDefs = new \ArrayObject();
86 46
        $complexity = 0;
87
88 46
        return $this->invokeIfNeeded(
89 46
            $context,
90
            [
91
                // Visit FragmentDefinition after visiting FragmentSpread
92 46
                'visitSpreadFragments' => true,
93
                Node::SELECTION_SET => function (SelectionSet $selectionSet) use ($context) {
94 12
                    $this->fieldAstAndDefs = $this->collectFieldASTsAndDefs(
95 12
                        $context,
96 12
                        $context->getParentType(),
97 12
                        $selectionSet,
98 12
                        null,
99 12
                        $this->fieldAstAndDefs
100 12
                    );
101 46
                },
102
                Node::VARIABLE_DEFINITION => function ($def) {
103 1
                    $this->variableDefs[] = $def;
104
105 1
                    return Visitor::skipNode();
106 46
                },
107 46
                Node::OPERATION_DEFINITION => [
108 46
                    'leave' => function (OperationDefinition $operationDefinition) use ($context, &$complexity) {
109 12
                        $complexity = $this->fieldComplexity($operationDefinition, $complexity);
110
111 12
                        if ($complexity > $this->getMaxQueryComplexity()) {
112 11
                            return new Error($this->maxQueryComplexityErrorMessage($this->getMaxQueryComplexity(), $complexity));
113
                        }
114 46
                    },
115 46
                ],
116
            ]
117 46
        );
118
    }
119
120 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...
121
    {
122 12
        if (isset($node->selectionSet)) {
123 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...
124 12
                $complexity = $this->nodeComplexity($childNode, $complexity);
125 12
            }
126 12
        }
127
128 12
        return $complexity;
129
    }
130
131 12
    private function nodeComplexity(Node $node, $complexity = 0)
132
    {
133 12
        switch ($node->kind) {
134 12
            case Node::FIELD:
135
                /* @var Field $node */
136
                // default values
137 12
                $args = [];
138 12
                $complexityFn = \Overblog\GraphQLBundle\Definition\FieldDefinition::DEFAULT_COMPLEXITY_FN;
139
140
                // calculate children complexity if needed
141 12
                $childrenComplexity = 0;
142
143
                // node has children?
144 12
                if (isset($node->selectionSet)) {
145 12
                    $childrenComplexity = $this->fieldComplexity($node);
146 12
                }
147
148 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...
149 12
                $fieldDef = $astFieldInfo[1];
150
151 12
                if ($fieldDef instanceof FieldDefinition) {
152 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...
153
                    //get complexity fn using fieldDef complexity
154 12
                    if (method_exists($fieldDef, 'getComplexityFn')) {
155 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...
156 10
                    }
157 12
                }
158
159 12
                $complexity += call_user_func_array($complexityFn, [$childrenComplexity, $args]);
160 12
                break;
161
162 3
            case Node::INLINE_FRAGMENT:
163
                /* @var InlineFragment $node */
164
                // node has children?
165 1
                if (isset($node->selectionSet)) {
166 1
                    $complexity = $this->fieldComplexity($node, $complexity);
167 1
                }
168 1
                break;
169
170 2
            case Node::FRAGMENT_SPREAD:
171
                /* @var FragmentSpread $node */
172 2
                $fragment = $this->getFragment($node);
173
174 2
                if (null !== $fragment) {
175 2
                    $complexity = $this->fieldComplexity($fragment, $complexity);
176 2
                }
177 2
                break;
178 12
        }
179
180 12
        return $complexity;
181
    }
182
183 12
    private function astFieldInfo(Field $field)
184
    {
185 12
        $fieldName = $this->getFieldName($field);
186 12
        $astFieldInfo = [null, null];
187 12
        if (isset($this->fieldAstAndDefs[$fieldName])) {
188 12
            foreach ($this->fieldAstAndDefs[$fieldName] as $astAndDef) {
189 12
                if ($astAndDef[0] == $field) {
190 12
                    $astFieldInfo = $astAndDef;
191 12
                    break;
192
                }
193 12
            }
194 12
        }
195
196 12
        return $astFieldInfo;
197
    }
198
199 12
    private function buildFieldArguments(Field $node)
200
    {
201 12
        $rawVariableValues = $this->getRawVariableValues();
202 12
        $astFieldInfo = $this->astFieldInfo($node);
203 12
        $fieldDef = $astFieldInfo[1];
204
205 12
        $args = [];
206
207 12
        if ($fieldDef instanceof FieldDefinition) {
208 12
            $variableValues = Values::getVariableValues(
209 12
                $this->context->getSchema(),
210 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...
211
                $rawVariableValues
212 12
            );
213 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...
214 12
        }
215
216 12
        return $args;
217
    }
218
219 46
    protected function isEnabled()
220
    {
221 46
        return $this->getMaxQueryComplexity() !== static::DISABLED;
222
    }
223
}
224