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 (#275)
by Hugo
15:12
created

Configuration::builderSection()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
ccs 22
cts 22
cp 1
rs 8.5806
cc 4
eloc 21
nc 1
nop 1
crap 4
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
                    ->end()
99 27
                ->end()
100 27
            ->end();
101
102 27
        return $node;
103
    }
104
105 27
    private function definitionsSection()
106
    {
107 27
        $builder = new TreeBuilder();
108
        /** @var ArrayNodeDefinition $node */
109 27
        $node = $builder->root('definitions');
110
        $node
111 27
            ->addDefaultsIfNotSet()
112 27
            ->children()
113 27
                ->variableNode('default_resolver')->defaultValue([Resolver::class, 'defaultResolveFn'])->end()
114 27
                ->scalarNode('class_namespace')->defaultValue('Overblog\\GraphQLBundle\\__DEFINITIONS__')->end()
115 27
                ->scalarNode('cache_dir')->defaultValue($this->cacheDir.'/overblog/graphql-bundle/__definitions__')->end()
116 27
                ->booleanNode('use_classloader_listener')->defaultTrue()->end()
117 27
                ->booleanNode('auto_compile')->defaultTrue()->end()
118 27
                ->booleanNode('show_debug_info')->info('Show some performance stats in extensions')->defaultFalse()->end()
119 27
                ->booleanNode('config_validation')->defaultValue($this->debug)->end()
120 27
                ->append($this->definitionsSchemaSection())
121 27
                ->append($this->definitionsAutoMappingSection())
122 27
                ->append($this->definitionsMappingsSection())
123 27
                ->arrayNode('builders')
124 27
                    ->children()
125 27
                        ->append($this->builderSection('field'))
126 27
                        ->append($this->builderSection('args'))
127 27
                    ->end()
128 27
                ->end()
129
130 27
            ->end()
131 27
        ->end();
132
133 27
        return $node;
134
    }
135
136 27
    private function servicesSection()
137
    {
138 27
        $builder = new TreeBuilder();
139
        /** @var ArrayNodeDefinition $node */
140 27
        $node = $builder->root('services');
141
        $node
142 27
            ->addDefaultsIfNotSet()
143 27
            ->children()
144 27
                ->scalarNode('executor')
145 27
                    ->defaultValue(self::NAME.'.executor.default')
146 27
                ->end()
147 27
                ->scalarNode('promise_adapter')
148 27
                    ->defaultValue(self::NAME.'.promise_adapter.default')
149 27
                ->end()
150 27
                ->scalarNode('expression_language')
151 27
                    ->defaultValue(self::NAME.'.expression_language.default')
152 27
                ->end()
153 27
                ->scalarNode('cache_expression_language_parser')
154 27
                    ->defaultValue(self::NAME.'.cache_expression_language_parser.default')
155 27
                ->end()
156 27
            ->end()
157 27
        ->end();
158
159 27
        return $node;
160
    }
161
162 27
    private function securitySection()
163
    {
164 27
        $builder = new TreeBuilder();
165
        /** @var ArrayNodeDefinition $node */
166 27
        $node = $builder->root('security');
167
        $node
168 27
            ->addDefaultsIfNotSet()
169 27
            ->children()
170 27
                ->append($this->securityQuerySection('query_max_depth', QueryDepth::DISABLED))
171 27
                ->append($this->securityQuerySection('query_max_complexity', QueryComplexity::DISABLED))
172 27
                ->booleanNode('handle_cors')->defaultFalse()->end()
173 27
            ->end()
174 27
        ->end();
175
176 27
        return $node;
177
    }
178
179 27
    private function definitionsSchemaSection()
180
    {
181 27
        $builder = new TreeBuilder();
182
        /** @var ArrayNodeDefinition $node */
183 27
        $node = $builder->root('schema');
184
        $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...
185 27
            ->beforeNormalization()
186 27
                ->ifTrue(function ($v) {
187 23
                    return isset($v['query']) && is_string($v['query']) || isset($v['mutation']) && is_string($v['mutation']);
188 27
                })
189 27
                ->then(function ($v) {
190 23
                    return ['default' => $v];
191 27
                })
192 27
            ->end()
193 27
            ->useAttributeAsKey('name')
194 27
            ->prototype('array')
195 27
                ->addDefaultsIfNotSet()
196 27
                ->children()
197 27
                    ->scalarNode('query')->defaultNull()->end()
198 27
                    ->scalarNode('mutation')->defaultNull()->end()
199 27
                    ->scalarNode('subscription')->defaultNull()->end()
200 27
                ->end()
201 27
            ->end()
202 27
        ->end();
203
204 27
        return $node;
205
    }
206
207 27
    private function definitionsAutoMappingSection()
208
    {
209 27
        $builder = new TreeBuilder();
210
        /** @var ArrayNodeDefinition $node */
211 27
        $node = $builder->root('auto_mapping');
212
        $node
213 27
            ->treatFalseLike(['enabled' => false])
214 27
            ->treatTrueLike(['enabled' => true])
215 27
            ->treatNullLike(['enabled' => true])
216 27
            ->addDefaultsIfNotSet()
217 27
            ->children()
218 27
                ->booleanNode('enabled')->defaultTrue()->end()
219 27
                ->arrayNode('directories')
220 27
                    ->info('List of directories containing GraphQL classes.')
221 27
                    ->prototype('scalar')->end()
222 27
                ->end()
223 27
            ->end()
224 27
        ->end();
225
226 27
        return $node;
227
    }
228
229 27
    private function definitionsMappingsSection()
230
    {
231 27
        $builder = new TreeBuilder();
232
        /** @var ArrayNodeDefinition $node */
233 27
        $node = $builder->root('mappings');
234
        $node
235 27
            ->children()
236 27
                ->arrayNode('auto_discover')
237 27
                    ->treatFalseLike(['bundles' => false, 'root_dir' => false])
238 27
                    ->treatTrueLike(['bundles' => true, 'root_dir' => true])
239 27
                    ->treatNullLike(['bundles' => true, 'root_dir' => true])
240 27
                    ->addDefaultsIfNotSet()
241 27
                    ->children()
242 27
                        ->booleanNode('bundles')->defaultTrue()->end()
243 27
                        ->booleanNode('root_dir')->defaultTrue()->end()
244 27
                    ->end()
245 27
                ->end()
246 27
                ->arrayNode('types')
247 27
                    ->prototype('array')
248 27
                        ->addDefaultsIfNotSet()
249 27
                        ->beforeNormalization()
250 27
                            ->ifTrue(function ($v) {
251 22
                                return isset($v['type']) && 'yml' === $v['type'];
252 27
                            })
253 27
                            ->then(function ($v) {
254 7
                                $v['type'] = 'yaml';
255
256 7
                                return $v;
257 27
                            })
258 27
                        ->end()
259 27
                        ->children()
260 27
                            ->enumNode('type')->values(['yaml', 'xml'])->defaultNull()->end()
261 27
                            ->scalarNode('dir')->defaultNull()->end()
262 27
                            ->scalarNode('suffix')->defaultValue(OverblogGraphQLTypesExtension::DEFAULT_TYPES_SUFFIX)->end()
263 27
                        ->end()
264 27
                    ->end()
265 27
                ->end()
266 27
            ->end()
267 27
        ->end();
268
269 27
        return $node;
270
    }
271
272
    /**
273
     * @param string $name
274
     *
275
     * @return ArrayNodeDefinition
276
     */
277 27
    private function builderSection($name)
278
    {
279 27
        $builder = new TreeBuilder();
280
        /** @var ArrayNodeDefinition $node */
281 27
        $node = $builder->root($name);
282 27
        $node->beforeNormalization()
283 27
            ->ifTrue(function ($v) {
284 1
                return is_array($v) && !empty($v);
285 27
            })
286 27
            ->then(function ($v) {
287 1
                foreach ($v as $key => &$config) {
288 1
                    if (is_string($config)) {
289
                        $config = [
290 1
                            'alias' => $key,
291 1
                            'class' => $config,
292
                        ];
293
                    }
294
                }
295
296 1
                return $v;
297 27
            })
298 27
        ->end();
299
300 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...
301 27
            ->children()
302 27
                ->scalarNode('alias')->isRequired()->end()
303 27
                ->scalarNode('class')->isRequired()->end()
304 27
            ->end()
305 27
        ->end()
306
        ;
307
308 27
        return $node;
309
    }
310
311
    /**
312
     * @param string $name
313
     * @param bool   $disabledValue
314
     *
315
     * @return ScalarNodeDefinition
316
     */
317 27
    private function securityQuerySection($name, $disabledValue)
318
    {
319 27
        $builder = new TreeBuilder();
320
        /** @var ScalarNodeDefinition $node */
321 27
        $node = $builder->root($name, 'scalar');
322 27
        $node->beforeNormalization()
323 27
                ->ifTrue(function ($v) {
324 25
                    return is_string($v) && is_numeric($v);
325 27
                })
326 27
                ->then(function ($v) {
327 2
                    return (int) $v;
328 27
                })
329 27
            ->end();
330
331
        $node
332 27
            ->info('Disabled if equal to false.')
333 27
            ->beforeNormalization()
334 27
                ->ifTrue(function ($v) {
335 25
                    return false === $v;
336 27
                })
337 27
                ->then(function () use ($disabledValue) {
338 25
                    return $disabledValue;
339 27
                })
340 27
            ->end()
341 27
            ->defaultFalse()
342 27
            ->validate()
343 27
                ->ifTrue(function ($v) {
344 25
                    return is_int($v) && $v < 0;
345 27
                })
346 27
                ->thenInvalid(sprintf('"%s.security.%s" must be greater or equal to 0.', self::NAME, $name))
347 27
            ->end()
348
        ;
349
350 27
        return $node;
351
    }
352
}
353