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 (#325)
by Jérémiah
13:59
created

Configuration::definitionsSection()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 1

Importance

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