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 (#333)
by Jérémiah
08:28 queued 05:48
created

Configuration::definitionsAutoMappingSection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 1

Importance

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