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