SpecificationConfiguration::addErrorShapeSection()   C
last analyzed

Complexity

Conditions 14
Paths 1

Size

Total Lines 74
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 53
CRAP Score 14.3115

Importance

Changes 0
Metric Value
dl 0
loc 74
ccs 53
cts 60
cp 0.8833
rs 5.3785
c 0
b 0
f 0
cc 14
eloc 60
nc 1
nop 2
crap 14.3115

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of indragunawan/rest-service package.
5
 *
6
 * (c) Indra Gunawan <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace IndraGunawan\RestService\Validator;
13
14
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
15
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
16
use Symfony\Component\Config\Definition\ConfigurationInterface;
17
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
18
19
/**
20
 * This is the class that validates and merges configuration.
21
 */
22
class SpecificationConfiguration implements ConfigurationInterface
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27 8
    public function getConfigTreeBuilder()
28
    {
29 8
        $treeBuilder = new TreeBuilder();
30 8
        $rootNode = $treeBuilder->root('rest_service');
31
32
        $rootNode
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...
33 8
            ->validate()
34 8
                ->always(function ($v) {
35 5
                    foreach ($v['operations'] as $name => $operation) {
36 5
                        if (!$operation['requestProtocol']) {
37 5
                            $v['operations'][$name]['requestProtocol'] = $v['protocol'];
38
                        }
39 5
                        if (!$operation['responseProtocol']) {
40 5
                            $v['operations'][$name]['responseProtocol'] = $v['protocol'];
41
                        }
42
                    }
43
44 5
                    return $v;
45 8
                })
46 8
            ->end()
47 8
            ->children()
48 8
                ->scalarNode('name')
49 8
                    ->cannotBeEmpty()
50 8
                    ->defaultNull()
51 8
                ->end() // name
52 8
                ->scalarNode('version')
53 8
                    ->cannotBeEmpty()
54 8
                    ->defaultNull()
55 8
                ->end() // version
56 8
                ->scalarNode('endpoint')
57 8
                    ->isRequired()
58 8
                    ->cannotBeEmpty()
59 8
                ->end() // endpoint
60 8
                ->scalarNode('description')
61 8
                    ->cannotBeEmpty()
62 8
                    ->defaultNull()
63 8
                ->end() // description
64 8
                ->scalarNode('documentationUrl')
65 8
                    ->cannotBeEmpty()
66 8
                    ->defaultNull()
67 8
                ->end() // documentationUrl
68 8
                ->scalarNode('protocol')
69 8
                    ->cannotBeEmpty()
70 8
                    ->defaultValue('rest_json')
71 8
                    ->validate()
72 8
                        ->ifNotInArray(['rest_json'])
73 8
                        ->thenInvalid('Invalid Protocol %s, Available protocols are "rest_json"')
74 8
                    ->end()
75 8
                ->end() // protocol
76 8
                ->append($this->getDefaultNode())
77 8
                ->append($this->getOperationNode())
78 8
                ->append($this->getShapeNode())
79 8
                ->append($this->getErrorShapeNode())
80 8
            ->end() // rest_service children
81
        ;
82
83 8
        return $treeBuilder;
84
    }
85
86 8
    private function getDefaultNode()
87
    {
88 8
        $treeBuilder = new TreeBuilder();
89 8
        $node = $treeBuilder->root('defaults');
90
91
        $node
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...
92 8
            ->useAttributeAsKey('name')
93 8
            ->prototype('array')
94 8
                ->children()
95 8
                    ->scalarNode('rule')
96 8
                        ->cannotBeEmpty()
97 8
                        ->defaultNull()
98 8
                    ->end() // rule
99 8
                    ->scalarNode('defaultValue')
100 8
                        ->cannotBeEmpty()
101 8
                        ->defaultValue('')
102 8
                    ->end() // defaultValue
103 8
                ->end() // default children
104 8
            ->end() // defaults prototype
105
        ;
106
107 8
        return $node;
108
    }
109
110 8
    private function getOperationNode()
111
    {
112 8
        $treeBuilder = new TreeBuilder();
113
114
        $availableHttpMethods = [
115 8
            'GET', 'POST', 'PUT', 'PATCH',
116
            'DELETE', 'HEAD', 'OPTIONS',
117
        ];
118
119
        $node = $treeBuilder
120 8
            ->root('operations')
121 8
            ->isRequired()
122 8
            ->requiresAtLeastOneElement()
123 8
            ->useAttributeAsKey('name')
124
        ;
125
126 8
        $operationNode = $node->prototype('array');
127
128
        $operationNode
129 8
            ->children()
130 8
                ->scalarNode('httpMethod')
131 8
                    ->isRequired()
132 8
                    ->beforeNormalization()
133 8
                        ->ifString()
134 8
                        ->then(function ($v) {
135 7
                            return strtoupper($v);
136 8
                        })
137 8
                    ->end()
138 8
                    ->validate()
139 8
                        ->ifNotInArray($availableHttpMethods)
140 8
                        ->thenInvalid('Invalid HTTP Method %s, Available methods are "'.implode('", "', $availableHttpMethods).'"')
141 8
                    ->end() // validate
142 8
                ->end() // httpMethod
143 8
                ->scalarNode('requestUri')
144 8
                    ->isRequired()
145 8
                    ->cannotBeEmpty()
146 8
                    ->validate()
147 8
                        ->ifString()
148 8
                        ->then(function ($v) {
149 5
                            return '/'.ltrim($v, '/');
150 8
                        })
151 8
                    ->end()
152 8
                ->end()
153 8
                ->scalarNode('description')
154 8
                    ->cannotBeEmpty()
155 8
                    ->defaultNull()
156 8
                ->end() // description
157 8
                ->scalarNode('documentationUrl')
158 8
                    ->cannotBeEmpty()
159 8
                    ->defaultNull()
160 8
                ->end() // documentationUrl
161 8
                ->scalarNode('requestProtocol')
162 8
                    ->cannotBeEmpty()
163 8
                    ->defaultNull()
164 8
                    ->validate()
165 8
                        ->ifNotInArray(['rest_json', 'form_params'])
166 8
                        ->thenInvalid('Invalid Protocol %s, Available protocols are "rest_json", "form_params"')
167 8
                    ->end()
168 8
                ->end() // requestProtocol
169 8
                ->scalarNode('responseProtocol')
170 8
                    ->cannotBeEmpty()
171 8
                    ->defaultNull()
172 8
                    ->validate()
173 8
                        ->ifNotInArray(['rest_json', 'stream'])
174 8
                        ->thenInvalid('Invalid Protocol %s, Available protocols are "rest_json", "stream"')
175 8
                    ->end()
176 8
                ->end() // responseProtocol
177 8
                ->booleanNode('strictRequest')
178 8
                    ->defaultFalse()
179 8
                ->end() // strictRequest
180 8
                ->booleanNode('strictResponse')
181 8
                    ->defaultFalse()
182 8
                ->end() // strictResponse
183 8
                ->booleanNode('sentEmptyField')
184 8
                    ->defaultTrue()
185 8
                ->end()
186
        ;
187
188
        $requestNode = $operationNode
189 8
            ->children()
190 8
                ->arrayNode('request')
191
        ;
192 8
        $this->addShapeSection($requestNode);
193
194
        $responseNode = $operationNode
195 8
            ->children()
196 8
                ->arrayNode('response')
197
        ;
198 8
        $this->addShapeSection($responseNode);
199
200
        $errorsNode = $operationNode
201 8
            ->children()
202 8
                ->arrayNode('errors')
203 8
                    ->prototype('array')
204
        ;
205 8
        $this->addErrorShapeSection($errorsNode);
206
207 8
        return $node;
208
    }
209
210 8
    private function getShapeNode()
211
    {
212 8
        $treeBuilder = new TreeBuilder();
213
        $node = $treeBuilder
214 8
            ->root('shapes')
215 8
            ->useAttributeAsKey('name')
216
        ;
217
218 8
        $this->addShapeSection($node->prototype('array'), false);
0 ignored issues
show
Compatibility introduced by
$node->prototype('array') of type object<Symfony\Component...Builder\NodeDefinition> is not a sub-type of object<Symfony\Component...er\ArrayNodeDefinition>. It seems like you assume a child class of the class Symfony\Component\Config...\Builder\NodeDefinition to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
219
220 8
        return $node;
221
    }
222
223 8
    private function getErrorShapeNode()
224
    {
225 8
        $treeBuilder = new TreeBuilder();
226
        $node = $treeBuilder
227 8
            ->root('errorShapes')
228 8
            ->useAttributeAsKey('name')
229
        ;
230
231 8
        $this->addErrorShapeSection($node->prototype('array'), false);
0 ignored issues
show
Compatibility introduced by
$node->prototype('array') of type object<Symfony\Component...Builder\NodeDefinition> is not a sub-type of object<Symfony\Component...er\ArrayNodeDefinition>. It seems like you assume a child class of the class Symfony\Component\Config...\Builder\NodeDefinition to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
232
233 8
        return $node;
234
    }
235
236 8
    private function addShapeSection(ArrayNodeDefinition $rootNode, $fromOperation = true)
237
    {
238 8
        $availableLocations = ['header', 'uri', 'query', 'body'];
239 8
        $availableTypes = ['map', 'list'];
240 8
        $availableMemberTypes = ['map', 'list', 'string', 'integer', 'float', 'number', 'boolean', 'datetime'];
241
        // map = object
242
        // list = array
243
244
        $rootNode
245 8
            ->beforeNormalization()
246 8
                ->always(function ($v) use ($fromOperation) {
247 2
                    if (!$fromOperation) {
248 2
                        if (isset($v['shape'])) {
249 1
                            throw new InvalidConfigurationException('Unrecognized option "shape"');
250
                        }
251
                    }
252
253 2
                    if (isset($v['shape']) && (isset($v['type']) || isset($v['members']))) {
254
                        throw new InvalidConfigurationException('Cannot combine "shape" with other properties.');
255
                    }
256
257 2
                    return $v;
258 8
                })
259 8
            ->end()
260 8
            ->children()
261 8
                ->scalarNode('shape')
262 8
                    ->cannotBeEmpty()
263 8
                    ->defaultNull()
264 8
                ->end()
265 8
                ->scalarNode('extends')
266 8
                    ->cannotBeEmpty()
267 8
                    ->defaultNull()
268 8
                ->end()
269 8
                ->scalarNode('type')
270 8
                    ->cannotBeEmpty()
271 8
                    ->defaultValue('map')
272 8
                    ->validate()
273 8
                        ->ifNotInArray($availableTypes)
274 8
                        ->thenInvalid('Invalid type %s, Available types are "'.implode('", "', $availableTypes).'"')
275 8
                    ->end() // validate
276 8
                ->end() // type
277 8
                ->arrayNode('members')
278 8
                    ->beforeNormalization()
279 8
                        ->ifArray()
280 8
                        ->then(function ($v) {
281 1
                            foreach ($v as $name => $member) {
282 1
                                if (!isset($member['locationName'])) {
283 1
                                    $v[$name]['locationName'] = $name;
284
                                }
285
286 1
                                if (isset($member['shape'])
287
                                    && (
288
                                        isset($member['location'])
289
                                        || isset($member['defaultValue'])
290 1
                                        || isset($member['format'])
291
                                    )
292
                                ) {
293
                                    throw new InvalidConfigurationException(sprintf(
294
                                        'Member "%s". Cannot combine "shape" with other properties.',
295
                                        $name
296
                                    ));
297
                                }
298
299 1
                                if (isset($member['shape']) && isset($member['type'])) {
300
                                    if (!in_array($member['type'], ['map', 'list'], true)) {
301
                                        throw new InvalidConfigurationException('type for shape only "map", "list"');
302
                                    }
303 1
                                } elseif (isset($member['type'])
304 1
                                    && !in_array($member['type'], ['string', 'datetime'], true)
305 1
                                    && isset($member['format'])
306
                                ) {
307 1
                                    throw new InvalidConfigurationException('"format" only for "string" or "datetime"');
308
                                }
309
                            }
310
311 1
                            return $v;
312 8
                        })
313 8
                    ->end()
314 8
                    ->useAttributeAsKey('name')
315 8
                    ->prototype('array')
316 8
                        ->children()
317 8
                            ->scalarNode('shape')
318 8
                                ->cannotBeEmpty()
319 8
                                ->defaultNull()
320 8
                            ->end() // shape
321 8
                            ->scalarNode('type')
322 8
                                ->cannotBeEmpty()
323 8
                                ->defaultValue('string')
324 8
                                ->validate()
325 8
                                    ->ifNotInArray($availableMemberTypes)
326 8
                                    ->thenInvalid('Invalid type %s, Available types are "'.implode('", "', $availableMemberTypes).'"')
327 8
                                ->end() // validate
328 8
                            ->end() // type
329 8
                            ->scalarNode('format')
330 8
                                ->cannotBeEmpty()
331 8
                                ->defaultNull()
332 8
                            ->end() // format
333 8
                            ->scalarNode('location')
334 8
                                ->defaultValue('body')
335 8
                                ->cannotBeEmpty()
336 8
                                ->validate()
337 8
                                    ->ifNotInArray($availableLocations)
338 8
                                    ->thenInvalid('Invalid shape location %s, Available methods are "'.implode('", "', $availableLocations).'"')
339 8
                                ->end() // validate
340 8
                            ->end() // location
341 8
                            ->scalarNode('locationName')
342 8
                                ->defaultNull()
343 8
                                ->cannotBeEmpty()
344 8
                            ->end() // locationName
345 8
                            ->scalarNode('rule')
346 8
                                ->defaultNull()
347 8
                                ->cannotBeEmpty()
348 8
                            ->end() // rule
349 8
                            ->scalarNode('defaultValue')
350 8
                                ->defaultValue('')
351 8
                                ->cannotBeEmpty()
352 8
                            ->end()
353 8
                        ->end() // member children
354 8
                    ->end() // members prototype
355 8
                ->end() // members
356 8
            ->end() // end
357
        ;
358 8
    }
359
360 8
    private function addErrorShapeSection(ArrayNodeDefinition $rootNode, $fromOperation = true)
361
    {
362 8
        $availableOperators = ['===', '!==', '==', '!=', '<', '<=', '>=', '>'];
363
        $rootNode
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...
364 8
            ->beforeNormalization()
365 8
                ->always(function ($v) use ($fromOperation) {
366 2
                    if (!$fromOperation) {
367 2
                        if (isset($v['errorShape'])) {
368 1
                            throw new InvalidConfigurationException('Unrecognized option "errorShape"');
369
                        }
370
                    }
371
372 2
                    if (isset($v['errorShape'])
373
                        && (
374
                            isset($v['type'])
375
                            || isset($v['codeField'])
376
                            || isset($v['ifCode'])
377
                            || isset($v['messageField'])
378 2
                            || isset($v['defaultMessage'])
379
                        )
380
                    ) {
381
                        throw new InvalidConfigurationException('Cannot combine "shape" with other properties.');
382
                    }
383
384 2
                    if (isset($v['type'])) {
385 1
                        if ('field' === $v['type'] && !isset($v['codeField'])) {
386
                            throw new InvalidConfigurationException('Error type "field", plesae provide "codeField" option.');
387 1
                        } elseif ('httpStatusCode' === $v['type'] && isset($v['codeField'])) {
388
                            throw new InvalidConfigurationException('Error type "httpStatusCode", Unrecognized option "codeField".');
389
                        }
390
                    }
391
392 2
                    return $v;
393 8
                })
394 8
            ->end()
395 8
            ->children()
396 8
                ->scalarNode('errorShape')
397 8
                    ->cannotBeEmpty()
398 8
                    ->defaultNull()
399 8
                ->end() // shape
400 8
                ->scalarNode('type')
401 8
                    ->cannotBeEmpty()
402 8
                    ->validate()
403 8
                        ->ifNotInArray(['httpStatusCode', 'field'])
404 8
                        ->thenInvalid('Invalid error type %s, Available error types are "httpStatusCode", "field"')
405 8
                    ->end() // validate
406 8
                ->end() // type
407 8
                ->scalarNode('codeField') // if type = field
408 8
                    ->cannotBeEmpty()
409 8
                    ->defaultNull()
410 8
                ->end() // codeField
411 8
                ->scalarNode('ifCode')
412 8
                    ->cannotBeEmpty()
413 8
                    ->defaultNull()
414 8
                ->end() // ifCode
415 8
                ->scalarNode('operator')
416 8
                    ->cannotBeEmpty()
417 8
                    ->defaultValue('==')
418 8
                    ->validate()
419 8
                        ->ifNotInArray($availableOperators)
420 8
                        ->thenInvalid('Invalid operator type %s, Available operators are "'.implode('", "', $availableOperators).'"')
421 8
                    ->end() // validate
422 8
                ->end() // operator
423 8
                ->scalarNode('messageField')
424 8
                    ->cannotBeEmpty()
425 8
                    ->defaultNull()
426 8
                ->end() // messageField
427 8
                ->scalarNode('defaultMessage')
428 8
                    ->cannotBeEmpty()
429 8
                    ->defaultNull()
430 8
                ->end() // defaultMessage
431 8
            ->end() // error children
432
        ;
433 8
    }
434
}
435