Passed
Push — master ( e3475b...d02991 )
by Bogdan
03:12
created

ParameterSpecBuilder::buildDefaultValue()   C

Complexity

Conditions 12
Paths 10

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 12.144

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 18
cts 20
cp 0.9
rs 5.1612
c 0
b 0
f 0
cc 12
eloc 20
nc 10
nop 1
crap 12.144

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
        (?:
38
            (?<type>(\w+\b(?:\(.*\))?)(?:\s*\|\s*(?-1))*)
39
            \s*
40
        )
41
        (?<name>[_a-z]\w*)
42
        (?:
43
            \s* = \s*
44
            (?<default>
45
                (?:[+-]?[0-9]+\.?[0-9]*)    # numbers (no exponential notation)
46
                |
47
                (?:\\\'[^\\\']*\\\')        # single-quoted string
48
                |
49
                (?:\"[^\"]*\")              # double-quoted string
50
                |
51
                (?:\[\s*\])                 # empty array
52
                |
53
                true | false | null
54
            )
55
        )?
56
        $
57
        /xi';
58
    /**
59
     * @var ExtractorDefinitionBuilderInterface
60
     */
61
    private $builder;
62
63 37
    public function __construct(ExtractorDefinitionBuilderInterface $builder)
64
    {
65 37
        $this->builder = $builder;
66 37
    }
67
68
    /**
69
     * @param string $definition
70
     *
71
     * @return ParameterSpecInterface
72
     * @throws ParameterSpecBuilderException
73
     */
74 37
    public function build(string $definition): ParameterSpecInterface
75
    {
76 37
        $definition = trim($definition);
77
78 37
        if (!$definition) {
79 1
            throw new ParameterSpecBuilderException('Definition must be non-empty string');
80
        }
81
82 36
        if (preg_match($this->regexp, $definition, $matches)) {
83
            try {
84 35
                if ($matches['rest'] ?? false) {
85 2
                    return $this->buildVariadicParameterSpec($matches);
86
                }
87
88 33
                if ($matches['default'] ?? false) {
89 29
                    return $this->buildOptionalParameterSpec($matches);
90
                }
91
92 4
                return $this->buildMandatoryParameterSpec($matches);
93 2
            } catch (ExtractorDefinitionBuilderException $e) {
94 1
                throw new ParameterSpecBuilderException("Unable to parse definition because of extractor failure: " . $e->getMessage());
95
            }
96
        }
97
98 1
        throw new ParameterSpecBuilderException("Unable to parse definition: '{$definition}'");
99
    }
100
101 2
    protected function buildVariadicParameterSpec(array $matches): VariadicParameterSpec
102
    {
103 2
        if (isset($matches['default'])) {
104 1
            throw new ParameterSpecBuilderException('Variadic parameter should have no default value');
105
        }
106
107 1
        return new VariadicParameterSpec($matches['name'], $this->builder->build($matches['type']));
108
    }
109
110 29
    protected function buildOptionalParameterSpec(array $matches): OptionalParameterSpec
111
    {
112 29
        $default = $this->buildDefaultValue($matches['default']);
113
114 29
        return new OptionalParameterSpec($matches['name'], $this->builder->build($matches['type']), $default);
115
    }
116
117 4
    protected function buildMandatoryParameterSpec(array $matches): MandatoryParameterSpec
118
    {
119 4
        return new MandatoryParameterSpec($matches['name'], $this->builder->build($matches['type']));
120
    }
121
122 29
    protected function buildDefaultValue(string $definition)
123
    {
124 29
        if (is_numeric($definition)) {
125 4
            if (false !== strpos($definition, '.')) {
126 2
                return (float)$definition;
127
            }
128
129 2
            return (int)$definition;
130
        }
131
132 25
        switch (strtolower($definition)) {
133 25
            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...
134 3
                return null;
135 22
            case 'true':
136 3
                return true;
137 19
            case 'false':
138 3
                return false;
139
        }
140
141
        // after this point all expected definition values MUST be at least 2 chars length
142
143 16
        if (strlen($definition) < 2) {
144
            // UNEXPECTED
145
            // Less likely we will ever get here because it should fail at a parsing step, but just in case
146
            throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
147
        }
148
149 16
        if ('[' == $definition[0] && ']' == $definition[-1]) {
150 2
            return [];
151
        }
152
153 14
        foreach (['"', "'"] as $quote) {
154 14
            if ($quote == $definition[0] && $quote == $definition[-1]) {
155 14
                return trim($definition, $quote);
156
            }
157
        }
158
159
        // Less likely we will ever get here because it should fail at a parsing step, but just in case
160
        throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
161
    }
162
}
163