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 (#333)
by Jérémiah
22:58
created

Configuration::definitionsMappingsSection()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 48
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 3

Importance

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