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
14:57
created

Configuration::definitionsMappingsSection()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 48
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 3

Importance

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