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 (#277)
by Jérémiah
20:41
created

Configuration::definitionsMappingsSection()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 48
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 3

Importance

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