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