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

Passed
Pull Request — master (#333)
by Jérémiah
14:59
created

Configuration::definitionsAutoMappingSection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
ccs 16
cts 16
cp 1
rs 9.584
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Overblog\GraphQLBundle\DependencyInjection;
4
5
use GraphQL\Validator\Rules\QueryComplexity;
6
use GraphQL\Validator\Rules\QueryDepth;
7
use Overblog\GraphQLBundle\Error\ErrorHandler;
8
use Overblog\GraphQLBundle\EventListener\ErrorLoggerListener;
9
use Overblog\GraphQLBundle\Resolver\Resolver;
10
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
11
use Symfony\Component\Config\Definition\Builder\EnumNodeDefinition;
12
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
13
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
14
use Symfony\Component\Config\Definition\ConfigurationInterface;
15
16
class Configuration implements ConfigurationInterface
17
{
18
    const NAME = 'overblog_graphql';
19
20
    /** bool */
21
    private $debug;
22
23
    /** null|string */
24
    private $cacheDir;
25
26
    /**
27
     * Constructor.
28
     *
29
     * @param bool        $debug    Whether to use the debug mode
30
     * @param null|string $cacheDir
31
     */
32 31
    public function __construct($debug, $cacheDir = null)
33
    {
34 31
        $this->debug = (bool) $debug;
35 31
        $this->cacheDir = $cacheDir;
36 31
    }
37
38 31
    public function getConfigTreeBuilder()
39
    {
40 31
        $treeBuilder = new TreeBuilder();
41 31
        $rootNode = $treeBuilder->root(self::NAME);
42
43
        $rootNode
44 31
            ->children()
45 31
                ->append($this->batchingMethodSection())
46 31
                ->append($this->definitionsSection())
47 31
                ->append($this->errorsHandlerSection())
48 31
                ->append($this->servicesSection())
49 31
                ->append($this->securitySection())
50 31
            ->end();
51
52 31
        return $treeBuilder;
53
    }
54
55 31
    private function batchingMethodSection()
56
    {
57 31
        $builder = new TreeBuilder();
58
        /** @var EnumNodeDefinition $node */
59 31
        $node = $builder->root('batching_method', 'enum');
60
61
        $node
0 ignored issues
show
Unused Code introduced by
The call to the method Symfony\Component\Config...umNodeDefinition::end() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
62 31
            ->values(['relay', 'apollo'])
63 31
            ->defaultValue('relay')
64 31
        ->end();
65
66 31
        return $node;
67
    }
68
69 31
    private function errorsHandlerSection()
70
    {
71 31
        $builder = new TreeBuilder();
72
        /** @var ArrayNodeDefinition $node */
73 31
        $node = $builder->root('errors_handler');
74
        $node
75 31
            ->treatFalseLike(['enabled' => false])
76 31
            ->treatTrueLike(['enabled' => true])
77 31
            ->treatNullLike(['enabled' => true])
78 31
            ->addDefaultsIfNotSet()
79 31
            ->children()
80 31
                ->booleanNode('enabled')->defaultTrue()->end()
81 31
                ->scalarNode('internal_error_message')->defaultValue(ErrorHandler::DEFAULT_ERROR_MESSAGE)->end()
82 31
                ->booleanNode('rethrow_internal_exceptions')->defaultFalse()->end()
83 31
                ->booleanNode('debug')->defaultValue($this->debug)->end()
84 31
                ->booleanNode('log')->defaultTrue()->end()
85 31
                ->scalarNode('logger_service')->defaultValue(ErrorLoggerListener::DEFAULT_LOGGER_SERVICE)->end()
86 31
                ->booleanNode('map_exceptions_to_parent')->defaultFalse()->end()
87 31
                ->arrayNode('exceptions')
88 31
                    ->addDefaultsIfNotSet()
89 31
                    ->children()
90 31
                        ->arrayNode('warnings')
91 31
                            ->treatNullLike([])
92 31
                            ->prototype('scalar')->end()
93 31
                        ->end()
94 31
                        ->arrayNode('errors')
95 31
                            ->treatNullLike([])
96 31
                            ->prototype('scalar')->end()
97 31
                    ->end()
98 31
                ->end()
99 31
            ->end();
100
101 31
        return $node;
102
    }
103
104 31
    private function definitionsSection()
105
    {
106 31
        $builder = new TreeBuilder();
107
        /** @var ArrayNodeDefinition $node */
108 31
        $node = $builder->root('definitions');
109
        $node
110 31
            ->addDefaultsIfNotSet()
111 31
            ->children()
112 31
                ->variableNode('default_resolver')->defaultValue([Resolver::class, 'defaultResolveFn'])->end()
113 31
                ->scalarNode('class_namespace')->defaultValue('Overblog\\GraphQLBundle\\__DEFINITIONS__')->end()
114 31
                ->scalarNode('cache_dir')->defaultNull()->end()
115 31
                ->booleanNode('use_classloader_listener')->defaultTrue()->end()
116 31
                ->booleanNode('auto_compile')->defaultTrue()->end()
117 31
                ->booleanNode('show_debug_info')->info('Show some performance stats in extensions')->defaultFalse()->end()
118 31
                ->booleanNode('config_validation')->defaultValue($this->debug)->end()
119 31
                ->append($this->definitionsSchemaSection())
120 31
                ->append($this->definitionsMappingsSection())
121 31
                ->arrayNode('builders')
122 31
                    ->children()
123 31
                        ->append($this->builderSection('field'))
124 31
                        ->append($this->builderSection('args'))
125 31
                    ->end()
126 31
                ->end()
127
128 31
            ->end()
129 31
        ->end();
130
131 31
        return $node;
132
    }
133
134 31
    private function servicesSection()
135
    {
136 31
        $builder = new TreeBuilder();
137
        /** @var ArrayNodeDefinition $node */
138 31
        $node = $builder->root('services');
139
        $node
140 31
            ->addDefaultsIfNotSet()
141 31
            ->children()
142 31
                ->scalarNode('executor')
143 31
                    ->defaultValue(self::NAME.'.executor.default')
144 31
                ->end()
145 31
                ->scalarNode('promise_adapter')
146 31
                    ->defaultValue(self::NAME.'.promise_adapter.default')
147 31
                ->end()
148 31
                ->scalarNode('expression_language')
149 31
                    ->defaultValue(self::NAME.'.expression_language.default')
150 31
                ->end()
151 31
                ->scalarNode('cache_expression_language_parser')->end()
152 31
            ->end()
153 31
        ->end();
154
155 31
        return $node;
156
    }
157
158 31
    private function securitySection()
159
    {
160 31
        $builder = new TreeBuilder();
161
        /** @var ArrayNodeDefinition $node */
162 31
        $node = $builder->root('security');
163
        $node
164 31
            ->addDefaultsIfNotSet()
165 31
            ->children()
166 31
                ->append($this->securityQuerySection('query_max_depth', QueryDepth::DISABLED))
167 31
                ->append($this->securityQuerySection('query_max_complexity', QueryComplexity::DISABLED))
168 31
                ->booleanNode('enable_introspection')->defaultTrue()->end()
169 31
                ->booleanNode('handle_cors')->defaultFalse()->end()
170 31
            ->end()
171 31
        ->end();
172
173 31
        return $node;
174
    }
175
176 31
    private function definitionsSchemaSection()
177
    {
178 31
        $builder = new TreeBuilder();
179
        /** @var ArrayNodeDefinition $node */
180 31
        $node = $builder->root('schema');
181
        $node
0 ignored issues
show
Bug introduced by
The method useAttributeAsKey() does not exist on Symfony\Component\Config...\Builder\NodeDefinition. Did you maybe mean attribute()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
182 31
            ->beforeNormalization()
183 31
                ->ifTrue(function ($v) {
184 27
                    return isset($v['query']) && is_string($v['query']) || isset($v['mutation']) && is_string($v['mutation']);
185 31
                })
186 31
                ->then(function ($v) {
187 27
                    return ['default' => $v];
188 31
                })
189 31
            ->end()
190 31
            ->useAttributeAsKey('name')
191 31
            ->prototype('array')
192 31
                ->addDefaultsIfNotSet()
193 31
                ->children()
194 31
                    ->scalarNode('query')->defaultNull()->end()
195 31
                    ->scalarNode('mutation')->defaultNull()->end()
196 31
                    ->scalarNode('subscription')->defaultNull()->end()
197 31
                    ->arrayNode('resolver_maps')
198 31
                        ->defaultValue([])
199 31
                        ->prototype('scalar')->end()
200 31
                    ->end()
201 31
                    ->arrayNode('types')
202 31
                        ->defaultValue([])
203 31
                        ->prototype('scalar')->end()
204 31
                    ->end()
205 31
                ->end()
206 31
            ->end()
207 31
        ->end();
208
209 31
        return $node;
210
    }
211
212 31
    private function definitionsMappingsSection()
213
    {
214 31
        $builder = new TreeBuilder();
215 31
        $node = $builder->root('mappings');
216
        $node
217 31
            ->children()
218 31
                ->arrayNode('auto_discover')
219 31
                    ->treatFalseLike(['bundles' => false, 'root_dir' => false])
220 31
                    ->treatTrueLike(['bundles' => true, 'root_dir' => true])
221 31
                    ->treatNullLike(['bundles' => true, 'root_dir' => true])
222 31
                    ->addDefaultsIfNotSet()
223 31
                    ->children()
224 31
                        ->booleanNode('bundles')->defaultTrue()->end()
225 31
                        ->booleanNode('root_dir')->defaultTrue()->end()
226 31
                    ->end()
227 31
                ->end()
228 31
                ->arrayNode('types')
229 31
                    ->prototype('array')
230 31
                        ->addDefaultsIfNotSet()
231 31
                        ->beforeNormalization()
232 31
                            ->ifTrue(function ($v) {
233 27
                                return isset($v['type']) && is_string($v['type']);
234 31
                            })
235 31
                            ->then(function ($v) {
236 26
                                if ('yml' === $v['type']) {
237 7
                                    $v['types'] = ['yaml'];
238
                                } else {
239 19
                                    $v['types'] = [$v['type']];
240
                                }
241 26
                                unset($v['type']);
242
243 26
                                return $v;
244 31
                            })
245 31
                        ->end()
246 31
                        ->children()
247 31
                            ->arrayNode('types')
248 31
                                ->prototype('enum')->values(array_keys(OverblogGraphQLTypesExtension::SUPPORTED_TYPES_EXTENSIONS))->isRequired()->end()
249 31
                            ->end()
250 31
                            ->scalarNode('dir')->defaultNull()->end()
251 31
                            ->scalarNode('suffix')->defaultValue(OverblogGraphQLTypesExtension::DEFAULT_TYPES_SUFFIX)->end()
252 31
                        ->end()
253 31
                    ->end()
254 31
                ->end()
255 31
            ->end()
256
        ;
257
258 31
        return $node;
259
    }
260
261
    /**
262
     * @param string $name
263
     *
264
     * @return ArrayNodeDefinition
265
     */
266 31
    private function builderSection($name)
267
    {
268 31
        $builder = new TreeBuilder();
269
        /** @var ArrayNodeDefinition $node */
270 31
        $node = $builder->root($name);
271 31
        $node->beforeNormalization()
272 31
            ->ifTrue(function ($v) {
273 1
                return is_array($v) && !empty($v);
274 31
            })
275 31
            ->then(function ($v) {
276 1
                foreach ($v as $key => &$config) {
277 1
                    if (is_string($config)) {
278
                        $config = [
279 1
                            'alias' => $key,
280 1
                            'class' => $config,
281
                        ];
282
                    }
283
                }
284
285 1
                return $v;
286 31
            })
287 31
        ->end();
288
289 31
        $node->prototype('array')
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method children() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. 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...
290 31
            ->children()
291 31
                ->scalarNode('alias')->isRequired()->end()
292 31
                ->scalarNode('class')->isRequired()->end()
293 31
            ->end()
294 31
        ->end()
295
        ;
296
297 31
        return $node;
298
    }
299
300
    /**
301
     * @param string $name
302
     * @param bool   $disabledValue
303
     *
304
     * @return ScalarNodeDefinition
305
     */
306 31
    private function securityQuerySection($name, $disabledValue)
307
    {
308 31
        $builder = new TreeBuilder();
309
        /** @var ScalarNodeDefinition $node */
310 31
        $node = $builder->root($name, 'scalar');
311 31
        $node->beforeNormalization()
312 31
                ->ifTrue(function ($v) {
313 29
                    return is_string($v) && is_numeric($v);
314 31
                })
315 31
                ->then(function ($v) {
316 4
                    return (int) $v;
317 31
                })
318 31
            ->end();
319
320
        $node
321 31
            ->info('Disabled if equal to false.')
322 31
            ->beforeNormalization()
323 31
                ->ifTrue(function ($v) {
324 29
                    return false === $v;
325 31
                })
326 31
                ->then(function () use ($disabledValue) {
327 29
                    return $disabledValue;
328 31
                })
329 31
            ->end()
330 31
            ->defaultFalse()
331 31
            ->validate()
332 31
                ->ifTrue(function ($v) {
333 29
                    return is_int($v) && $v < 0;
334 31
                })
335 31
                ->thenInvalid(sprintf('"%s.security.%s" must be greater or equal to 0.', self::NAME, $name))
336 31
            ->end()
337
        ;
338
339 31
        return $node;
340
    }
341
}
342