Passed
Push — new-features ( 4436b0 )
by Bogdan
05:26 queued 02:19
created

ParameterSpecBuilder::buildDefaultValue()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 44
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 11.0908

Importance

Changes 0
Metric Value
dl 0
loc 44
ccs 20
cts 22
cp 0.9091
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 22
nc 11
nop 1
crap 11.0908

How to fix   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 the pinepain/js-sandbox PHP library.
5
 *
6
 * Copyright (c) 2016-2017 Bogdan Padalko <[email protected]>
7
 *
8
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
9
 *
10
 * For the full copyright and license information, please view the
11
 * LICENSE file that was distributed with this source or visit
12
 * http://opensource.org/licenses/MIT
13
 */
14
15
16
namespace Pinepain\JsSandbox\Specs\Builder;
17
18
19
use Pinepain\JsSandbox\Extractors\ExtractorDefinitionBuilderException;
20
use Pinepain\JsSandbox\Extractors\ExtractorDefinitionBuilderInterface;
21
use Pinepain\JsSandbox\Specs\Builder\Exceptions\ParameterSpecBuilderException;
22
use Pinepain\JsSandbox\Specs\Parameters\MandatoryParameterSpec;
23
use Pinepain\JsSandbox\Specs\Parameters\OptionalParameterSpec;
24
use Pinepain\JsSandbox\Specs\Parameters\ParameterSpecInterface;
25
use Pinepain\JsSandbox\Specs\Parameters\VariadicParameterSpec;
26
use function strlen;
27
28
29
class ParameterSpecBuilder implements ParameterSpecBuilderInterface
30
{
31
    protected $regexp = '/
32
        ^
33
        (?:
34
            (?<rest>\.{3})
35
            \s*
36
        )?
37
        (?<name>[_a-z]\w*)
38
        (?:
39
            \s* = \s*
40
            (?<default>
41
                (?:[+-]?[0-9]+\.?[0-9]*)    # numbers (no exponential notation)
42
                |
43
                (?:\\\'[^\\\']*\\\')        # single-quoted string
44
                |
45
                (?:\"[^\"]*\")              # double-quoted string
46
                |
47
                (?:\[\s*\])                 # empty array
48
                |
49
                (?:\{\s*\})                 # empty object
50
                |
51
                true | false | null
52
            )
53
            \s*
54
        )?
55
        (?:
56
            \s*
57
            \:
58
            \s*
59
            (?<type>(\w*(?:\(.*\))?(?:\[\s*\])?)(?:\s*\|\s*(?-1))*)
60
            \s*
61
        )?
62
        $
63
        /xi';
64
    /**
65
     * @var ExtractorDefinitionBuilderInterface
66
     */
67
    private $builder;
68
69 39
    public function __construct(ExtractorDefinitionBuilderInterface $builder)
70
    {
71 39
        $this->builder = $builder;
72 39
    }
73
74
    /**
75
     * @param string $definition
76
     *
77
     * @return ParameterSpecInterface
78
     * @throws ParameterSpecBuilderException
79
     */
80 39
    public function build(string $definition): ParameterSpecInterface
81
    {
82 39
        $definition = trim($definition);
83
84 39
        if (!$definition) {
85 1
            throw new ParameterSpecBuilderException('Definition must be non-empty string');
86
        }
87
88 38
        if (preg_match($this->regexp, $definition, $matches)) {
89
            try {
90 37
                if ($matches['rest'] ?? false) {
91 2
                    return $this->buildVariadicParameterSpec($matches);
92
                }
93
94 35
                if ($matches['default'] ?? false) {
95 31
                    return $this->buildOptionalParameterSpec($matches);
96
                }
97
98 4
                return $this->buildMandatoryParameterSpec($matches);
99 2
            } catch (ExtractorDefinitionBuilderException $e) {
100 1
                throw new ParameterSpecBuilderException("Unable to parse definition because of extractor failure: " . $e->getMessage());
101
            }
102
        }
103
104 1
        throw new ParameterSpecBuilderException("Unable to parse definition: '{$definition}'");
105
    }
106
107 2
    protected function buildVariadicParameterSpec(array $matches): VariadicParameterSpec
108
    {
109 2
        if (isset($matches['default']) && '' !== $matches['default']) {
110 1
            throw new ParameterSpecBuilderException('Variadic parameter should have no default value');
111
        }
112
113 1
        return new VariadicParameterSpec($matches['name'], $this->builder->build($matches['type']));
114
    }
115
116 31
    protected function buildOptionalParameterSpec(array $matches): OptionalParameterSpec
117
    {
118 31
        $default = $this->buildDefaultValue($matches['default']);
119
120 31
        return new OptionalParameterSpec($matches['name'], $this->builder->build($matches['type']), $default);
121
    }
122
123 4
    protected function buildMandatoryParameterSpec(array $matches): MandatoryParameterSpec
124
    {
125 4
        return new MandatoryParameterSpec($matches['name'], $this->builder->build($matches['type']));
126
    }
127
128 31
    protected function buildDefaultValue(string $definition)
129
    {
130 31
        if (is_numeric($definition)) {
131 4
            if (false !== strpos($definition, '.')) {
132 2
                return (float)$definition;
133
            }
134
135 2
            return (int)$definition;
136
        }
137
138 27
        switch (strtolower($definition)) {
139 27
            case 'null':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
140 3
                return null;
141 24
            case 'true':
142 3
                return true;
143 21
            case 'false':
144 3
                return false;
145
        }
146
147
        // after this point all expected definition values MUST be at least 2 chars length
148
149 18
        if (strlen($definition) < 2) {
150
            // UNEXPECTED
151
            // Less likely we will ever get here because it should fail at a parsing step, but just in case
152
            throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
153
        }
154
155 18
        if ($this->wrappedWith($definition, '[', ']')) {
156 2
            return [];
157
        }
158
159 16
        if ($this->wrappedWith($definition, '{', '}')) {
160 2
            return [];
161
        }
162
163 14
        foreach (['"', "'"] as $quote) {
164 14
            if ($this->wrappedWith($definition, $quote, $quote)) {
165 14
                return trim($definition, $quote);
166
            }
167
        }
168
169
        // Less likely we will ever get here because it should fail at a parsing step, but just in case
170
        throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
171
    }
172
173 18
    private function wrappedWith(string $definition, string $starts, $ends)
174
    {
175 18
        assert(strlen($definition) >= 2);
176
177 18
        return $starts == $definition[0] && $ends == $definition[-1];
178
    }
179
}
180