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
Push — master ( 921329...8d19ff )
by Jérémiah
17:19
created

Configuration::servicesSection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 18
cts 18
cp 1
rs 9.0856
c 0
b 0
f 0
cc 1
eloc 19
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 30
    public function __construct($debug, $cacheDir = null)
33
    {
34 30
        $this->debug = (bool) $debug;
35 30
        $this->cacheDir = $cacheDir;
36 30
    }
37
38 30
    public function getConfigTreeBuilder()
39
    {
40 30
        $treeBuilder = new TreeBuilder();
41 30
        $rootNode = $treeBuilder->root(self::NAME);
42
43
        $rootNode
44 30
            ->children()
45 30
                ->append($this->batchingMethodSection())
46 30
                ->append($this->definitionsSection())
47 30
                ->append($this->errorsHandlerSection())
48 30
                ->append($this->servicesSection())
49 30
                ->append($this->securitySection())
50 30
            ->end();
51
52 30
        return $treeBuilder;
53
    }
54
55 30
    private function batchingMethodSection()
56
    {
57 30
        $builder = new TreeBuilder();
58
        /** @var EnumNodeDefinition $node */
59 30
        $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 30
            ->values(['relay', 'apollo'])
63 30
            ->defaultValue('relay')
64 30
        ->end();
65
66 30
        return $node;
67
    }
68
69 30
    private function errorsHandlerSection()
70
    {
71 30
        $builder = new TreeBuilder();
72
        /** @var ArrayNodeDefinition $node */
73 30
        $node = $builder->root('errors_handler');
74
        $node
75 30
            ->treatFalseLike(['enabled' => false])
76 30
            ->treatTrueLike(['enabled' => true])
77 30
            ->treatNullLike(['enabled' => true])
78 30
            ->addDefaultsIfNotSet()
79 30
            ->children()
80 30
                ->booleanNode('enabled')->defaultTrue()->end()
81 30
                ->scalarNode('internal_error_message')->defaultValue(ErrorHandler::DEFAULT_ERROR_MESSAGE)->end()
82 30
                ->booleanNode('rethrow_internal_exceptions')->defaultFalse()->end()
83 30
                ->booleanNode('debug')->defaultValue($this->debug)->end()
84 30
                ->booleanNode('log')->defaultTrue()->end()
85 30
                ->scalarNode('logger_service')->defaultValue(ErrorLoggerListener::DEFAULT_LOGGER_SERVICE)->end()
86 30
                ->booleanNode('map_exceptions_to_parent')->defaultFalse()->end()
87 30
                ->arrayNode('exceptions')
88 30
                    ->addDefaultsIfNotSet()
89 30
                    ->children()
90 30
                        ->arrayNode('warnings')
91 30
                            ->treatNullLike([])
92 30
                            ->prototype('scalar')->end()
93 30
                        ->end()
94 30
                        ->arrayNode('errors')
95 30
                            ->treatNullLike([])
96 30
                            ->prototype('scalar')->end()
97 30
                    ->end()
98 30
                ->end()
99 30
            ->end();
100
101 30
        return $node;
102
    }
103
104 30
    private function definitionsSection()
105
    {
106 30
        $builder = new TreeBuilder();
107
        /** @var ArrayNodeDefinition $node */
108 30
        $node = $builder->root('definitions');
109
        $node
110 30
            ->addDefaultsIfNotSet()
111 30
            ->children()
112 30
                ->variableNode('default_resolver')->defaultValue([Resolver::class, 'defaultResolveFn'])->end()
113 30
                ->scalarNode('class_namespace')->defaultValue('Overblog\\GraphQLBundle\\__DEFINITIONS__')->end()
114 30
                ->scalarNode('cache_dir')->defaultNull()->end()
115 30
                ->booleanNode('use_classloader_listener')->defaultTrue()->end()
116 30
                ->booleanNode('auto_compile')->defaultTrue()->end()
117 30
                ->booleanNode('show_debug_info')->info('Show some performance stats in extensions')->defaultFalse()->end()
118 30
                ->booleanNode('config_validation')->defaultValue($this->debug)->end()
119 30
                ->append($this->definitionsSchemaSection())
120 30
                ->append($this->definitionsAutoMappingSection())
121 30
                ->append($this->definitionsMappingsSection())
122 30
                ->arrayNode('builders')
123 30
                    ->children()
124 30
                        ->append($this->builderSection('field'))
125 30
                        ->append($this->builderSection('args'))
126 30
                    ->end()
127 30
                ->end()
128
129 30
            ->end()
130 30
        ->end();
131
132 30
        return $node;
133
    }
134
135 30
    private function servicesSection()
136
    {
137 30
        $builder = new TreeBuilder();
138
        /** @var ArrayNodeDefinition $node */
139 30
        $node = $builder->root('services');
140
        $node
141 30
            ->addDefaultsIfNotSet()
142 30
            ->children()
143 30
                ->scalarNode('executor')
144 30
                    ->defaultValue(self::NAME.'.executor.default')
145 30
                ->end()
146 30
                ->scalarNode('promise_adapter')
147 30
                    ->defaultValue(self::NAME.'.promise_adapter.default')
148 30
                ->end()
149 30
                ->scalarNode('expression_language')
150 30
                    ->defaultValue(self::NAME.'.expression_language.default')
151 30
                ->end()
152 30
                ->scalarNode('cache_expression_language_parser')->end()
153 30
            ->end()
154 30
        ->end();
155
156 30
        return $node;
157
    }
158
159 30
    private function securitySection()
160
    {
161 30
        $builder = new TreeBuilder();
162
        /** @var ArrayNodeDefinition $node */
163 30
        $node = $builder->root('security');
164
        $node
165 30
            ->addDefaultsIfNotSet()
166 30
            ->children()
167 30
                ->append($this->securityQuerySection('query_max_depth', QueryDepth::DISABLED))
168 30
                ->append($this->securityQuerySection('query_max_complexity', QueryComplexity::DISABLED))
169 30
                ->booleanNode('handle_cors')->defaultFalse()->end()
170 30
            ->end()
171 30
        ->end();
172
173 30
        return $node;
174
    }
175
176 30
    private function definitionsSchemaSection()
177
    {
178 30
        $builder = new TreeBuilder();
179
        /** @var ArrayNodeDefinition $node */
180 30
        $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 30
            ->beforeNormalization()
183 30
                ->ifTrue(function ($v) {
184 26
                    return isset($v['query']) && is_string($v['query']) || isset($v['mutation']) && is_string($v['mutation']);
185 30
                })
186 30
                ->then(function ($v) {
187 26
                    return ['default' => $v];
188 30
                })
189 30
            ->end()
190 30
            ->useAttributeAsKey('name')
191 30
            ->prototype('array')
192 30
                ->addDefaultsIfNotSet()
193 30
                ->children()
194 30
                    ->scalarNode('query')->defaultNull()->end()
195 30
                    ->scalarNode('mutation')->defaultNull()->end()
196 30
                    ->scalarNode('subscription')->defaultNull()->end()
197 30
                    ->arrayNode('resolver_maps')
198 30
                        ->defaultValue([])
199 30
                        ->prototype('scalar')->end()
200 30
                    ->end()
201 30
                    ->arrayNode('types')
202 30
                        ->defaultValue([])
203 30
                        ->prototype('scalar')->end()
204 30
                    ->end()
205 30
                ->end()
206 30
            ->end()
207 30
        ->end();
208
209 30
        return $node;
210
    }
211
212 30
    private function definitionsAutoMappingSection()
213
    {
214 30
        $builder = new TreeBuilder();
215
        /** @var ArrayNodeDefinition $node */
216 30
        $node = $builder->root('auto_mapping');
217
        $node
218 30
            ->treatFalseLike(['enabled' => false])
219 30
            ->treatTrueLike(['enabled' => true])
220 30
            ->treatNullLike(['enabled' => true])
221 30
            ->addDefaultsIfNotSet()
222 30
            ->children()
223 30
                ->booleanNode('enabled')->defaultTrue()->end()
224 30
                ->arrayNode('directories')
225 30
                    ->info('List of directories containing GraphQL classes.')
226 30
                    ->prototype('scalar')->end()
227 30
                ->end()
228 30
            ->end()
229 30
        ->end();
230
231 30
        return $node;
232
    }
233
234 30
    private function definitionsMappingsSection()
235
    {
236 30
        $builder = new TreeBuilder();
237 30
        $node = $builder->root('mappings');
238
        $node
239 30
            ->children()
240 30
                ->arrayNode('auto_discover')
241 30
                    ->treatFalseLike(['bundles' => false, 'root_dir' => false])
242 30
                    ->treatTrueLike(['bundles' => true, 'root_dir' => true])
243 30
                    ->treatNullLike(['bundles' => true, 'root_dir' => true])
244 30
                    ->addDefaultsIfNotSet()
245 30
                    ->children()
246 30
                        ->booleanNode('bundles')->defaultTrue()->end()
247 30
                        ->booleanNode('root_dir')->defaultTrue()->end()
248 30
                    ->end()
249 30
                ->end()
250 30
                ->arrayNode('types')
251 30
                    ->prototype('array')
252 30
                        ->addDefaultsIfNotSet()
253 30
                        ->beforeNormalization()
254 30
                            ->ifTrue(function ($v) {
255 25
                                return isset($v['type']) && is_string($v['type']);
256 30
                            })
257 30
                            ->then(function ($v) {
258 24
                                if ('yml' === $v['type']) {
259 7
                                    $v['types'] = ['yaml'];
260
                                } else {
261 17
                                    $v['types'] = [$v['type']];
262
                                }
263 24
                                unset($v['type']);
264
265 24
                                return $v;
266 30
                            })
267 30
                        ->end()
268 30
                        ->children()
269 30
                            ->arrayNode('types')
270 30
                                ->prototype('enum')->values(array_keys(OverblogGraphQLTypesExtension::SUPPORTED_TYPES_EXTENSIONS))->isRequired()->end()
271 30
                            ->end()
272 30
                            ->scalarNode('dir')->defaultNull()->end()
273 30
                            ->scalarNode('suffix')->defaultValue(OverblogGraphQLTypesExtension::DEFAULT_TYPES_SUFFIX)->end()
274 30
                        ->end()
275 30
                    ->end()
276 30
                ->end()
277 30
            ->end()
278
        ;
279
280 30
        return $node;
281
    }
282
283
    /**
284
     * @param string $name
285
     *
286
     * @return ArrayNodeDefinition
287
     */
288 30
    private function builderSection($name)
289
    {
290 30
        $builder = new TreeBuilder();
291
        /** @var ArrayNodeDefinition $node */
292 30
        $node = $builder->root($name);
293 30
        $node->beforeNormalization()
294 30
            ->ifTrue(function ($v) {
295 1
                return is_array($v) && !empty($v);
296 30
            })
297 30
            ->then(function ($v) {
298 1
                foreach ($v as $key => &$config) {
299 1
                    if (is_string($config)) {
300
                        $config = [
301 1
                            'alias' => $key,
302 1
                            'class' => $config,
303
                        ];
304
                    }
305
                }
306
307 1
                return $v;
308 30
            })
309 30
        ->end();
310
311 30
        $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...
312 30
            ->children()
313 30
                ->scalarNode('alias')->isRequired()->end()
314 30
                ->scalarNode('class')->isRequired()->end()
315 30
            ->end()
316 30
        ->end()
317
        ;
318
319 30
        return $node;
320
    }
321
322
    /**
323
     * @param string $name
324
     * @param bool   $disabledValue
325
     *
326
     * @return ScalarNodeDefinition
327
     */
328 30
    private function securityQuerySection($name, $disabledValue)
329
    {
330 30
        $builder = new TreeBuilder();
331
        /** @var ScalarNodeDefinition $node */
332 30
        $node = $builder->root($name, 'scalar');
333 30
        $node->beforeNormalization()
334 30
                ->ifTrue(function ($v) {
335 28
                    return is_string($v) && is_numeric($v);
336 30
                })
337 30
                ->then(function ($v) {
338 2
                    return (int) $v;
339 30
                })
340 30
            ->end();
341
342
        $node
343 30
            ->info('Disabled if equal to false.')
344 30
            ->beforeNormalization()
345 30
                ->ifTrue(function ($v) {
346 28
                    return false === $v;
347 30
                })
348 30
                ->then(function () use ($disabledValue) {
349 28
                    return $disabledValue;
350 30
                })
351 30
            ->end()
352 30
            ->defaultFalse()
353 30
            ->validate()
354 30
                ->ifTrue(function ($v) {
355 28
                    return is_int($v) && $v < 0;
356 30
                })
357 30
                ->thenInvalid(sprintf('"%s.security.%s" must be greater or equal to 0.', self::NAME, $name))
358 30
            ->end()
359
        ;
360
361 30
        return $node;
362
    }
363
}
364