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:19
created

QueryComplexity   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 195
Duplicated Lines 5.13 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 28
c 3
b 0
f 1
lcom 2
cbo 8
dl 10
loc 195
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A maxQueryComplexityErrorMessage() 0 4 1
A setMaxQueryComplexity() 0 6 1
A getMaxQueryComplexity() 0 4 1
A setRawVariableValues() 0 4 2
A getRawVariableValues() 0 4 1
B __invoke() 0 39 2
A fieldComplexity() 10 10 3
C nodeComplexity() 0 48 9
A astFieldInfo() 0 15 4
A buildFieldArguments() 0 19 2
A isEnabled() 0 4 1

How to fix   Duplicated Code   

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:

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
    public function __construct($maxQueryDepth = self::DEFAULT_QUERY_MAX_COMPLEXITY)
43
    {
44
        $this->setMaxQueryComplexity($maxQueryDepth);
45
    }
46
47
    public static function maxQueryComplexityErrorMessage($max, $count)
48
    {
49
        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
    public static function setMaxQueryComplexity($maxQueryComplexity)
58
    {
59
        self::checkIfGreaterOrEqualToZero('maxQueryComplexity', $maxQueryComplexity);
60
61
        self::$maxQueryComplexity = (int) $maxQueryComplexity;
62
    }
63
64
    public static function getMaxQueryComplexity()
65
    {
66
        return self::$maxQueryComplexity;
67
    }
68
69
    public static function setRawVariableValues(array $rawVariableValues = null)
70
    {
71
        self::$rawVariableValues = $rawVariableValues ?: [];
72
    }
73
74
    public static function getRawVariableValues()
75
    {
76
        return self::$rawVariableValues;
77
    }
78
79
    public function __invoke(ValidationContext $context)
80
    {
81
        $this->context = $context;
82
83
        $this->variableDefs = new \ArrayObject();
84
        $this->fieldAstAndDefs = new \ArrayObject();
85
        $complexity = 0;
86
87
        return $this->invokeIfNeeded(
88
            $context,
89
            [
90
                // Visit FragmentDefinition after visiting FragmentSpread
91
                'visitSpreadFragments' => true,
92
                Node::SELECTION_SET => function (SelectionSet $selectionSet) use ($context) {
93
                    $this->fieldAstAndDefs = $this->collectFieldASTsAndDefs(
94
                        $context,
95
                        $context->getParentType(),
96
                        $selectionSet,
97
                        null,
98
                        $this->fieldAstAndDefs
99
                    );
100
                },
101
                Node::VARIABLE_DEFINITION => function ($def) {
102
                    $this->variableDefs[] = $def;
103
104
                    return Visitor::skipNode();
105
                },
106
                Node::OPERATION_DEFINITION => [
107
                    'leave' => function (OperationDefinition $operationDefinition) use ($context, &$complexity) {
108
                        $complexity = $this->fieldComplexity($operationDefinition, $complexity);
109
110
                        if ($complexity > $this->getMaxQueryComplexity()) {
111
                            return new Error($this->maxQueryComplexityErrorMessage($this->getMaxQueryComplexity(), $complexity));
112
                        }
113
                    },
114
                ],
115
            ]
116
        );
117
    }
118
119 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
        if (isset($node->selectionSet)) {
122
            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
                $complexity = $this->nodeComplexity($childNode, $complexity);
124
            }
125
        }
126
127
        return $complexity;
128
    }
129
130
    private function nodeComplexity(Node $node, $complexity = 0)
131
    {
132
        switch ($node->kind) {
133
            case Node::FIELD:
134
                // default values
135
                $args = [];
136
                $complexityFn = 'Overblog\GraphQLBundle\Definition\FieldDefinition::defaultComplexity';
137
138
                // calculate children complexity if needed
139
                $childrenComplexity = 0;
140
141
                // node has children?
142
                if (isset($node->selectionSet)) {
143
                    $childrenComplexity = $this->fieldComplexity($node);
144
                }
145
146
                $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
                $fieldDef = $astFieldInfo[1];
148
149
                if ($fieldDef instanceof FieldDefinition) {
150
                    $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
                    if (method_exists($fieldDef, 'getComplexityFn')) {
153
                        $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
                    }
155
                }
156
157
                $complexity += call_user_func_array($complexityFn, [$childrenComplexity, $args]);
158
                break;
159
160
            case Node::INLINE_FRAGMENT:
161
                // node has children?
162
                if (isset($node->selectionSet)) {
163
                    $complexity = $this->fieldComplexity($node, $complexity);
164
                }
165
                break;
166
167
            case Node::FRAGMENT_SPREAD:
168
                $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
                if (null !== $fragment) {
171
                    $complexity = $this->fieldComplexity($fragment, $complexity);
172
                }
173
                break;
174
        }
175
176
        return $complexity;
177
    }
178
179
    private function astFieldInfo(Field $field)
180
    {
181
        $fieldName = $this->getFieldName($field);
182
        $astFieldInfo = [null, null];
183
        if (isset($this->fieldAstAndDefs[$fieldName])) {
184
            foreach ($this->fieldAstAndDefs[$fieldName] as $astAndDef) {
185
                if ($astAndDef[0] == $field) {
186
                    $astFieldInfo = $astAndDef;
187
                    break;
188
                }
189
            }
190
        }
191
192
        return $astFieldInfo;
193
    }
194
195
    private function buildFieldArguments(Field $node)
196
    {
197
        $rawVariableValues = $this->getRawVariableValues();
198
        $astFieldInfo = $this->astFieldInfo($node);
199
        $fieldDef = $astFieldInfo[1];
200
201
        $args = [];
202
203
        if ($fieldDef instanceof FieldDefinition) {
204
            $variableValues = Values::getVariableValues(
205
                $this->context->getSchema(),
206
                $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
            );
209
            $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
        }
211
212
        return $args;
213
    }
214
215
    protected function isEnabled()
216
    {
217
        return $this->getMaxQueryComplexity() !== static::DISABLED;
218
    }
219
}
220