Passed
Push — wip-public-release ( a61434...47f00e )
by Bogdan
03:48
created

ParameterSpecBuilder::buildDefaultValue()   C

Complexity

Conditions 13
Paths 10

Size

Total Lines 40
Code Lines 21

Duplication

Lines 6
Ratio 15 %

Code Coverage

Tests 16
CRAP Score 15.2812

Importance

Changes 0
Metric Value
dl 6
loc 40
ccs 16
cts 21
cp 0.7619
rs 5.1234
c 0
b 0
f 0
cc 13
eloc 21
nc 10
nop 1
crap 15.2812

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/php-v8-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
27
use function strlen;
28
29
30
class ParameterSpecBuilder implements ParameterSpecBuilderInterface
31
{
32
    protected $regexp = '/
33
        ^
34
        (?:
35
            (?<rest>\.{3})
36
            \s*
37
        )?
38
        (?:
39
            (?<type>(\w+\b(?:\(.*\))?)(?:\s*\|\s*(?-1))*)
40
            \s*
41
        )
42
        (?<name>[_a-z]\w*)
43
        (?:
44
            \s* = \s*
45
            (?<default>
46
                (?:[+-]?[0-9]+\.?[0-9]*)    # numbers (no exponential notation)
47
                |
48
                (?:\\\'[^\\\']*\\\')        # single-quoted string
49
                |
50
                (?:\"[^\"]*\")              # double-quoted string
51
                |
52
                (?:\[\s*\])                 # empty array
53
                |
54
                true | false | null
55
            )
56
        )?
57
        $
58
        /xi';
59
    /**
60
     * @var ExtractorDefinitionBuilderInterface
61
     */
62
    private $builder;
63
64 37
    public function __construct(ExtractorDefinitionBuilderInterface $builder)
65
    {
66 37
        $this->builder = $builder;
67 37
    }
68
69
    /**
70
     * @param string $definition
71
     *
72
     * @return ParameterSpecInterface
73
     * @throws ParameterSpecBuilderException
74
     */
75 37
    public function build(string $definition): ParameterSpecInterface
76
    {
77 37
        $definition = trim($definition);
78
79 37
        if (!$definition) {
80 1
            throw new ParameterSpecBuilderException('Definition must be non-empty string');
81
        }
82
83 36
        if (preg_match($this->regexp, $definition, $matches)) {
84
            try {
85 35
                if ($matches['rest'] ?? false) {
86 2
                    return $this->buildVariadicParameterSpec($matches);
87
                }
88
89 33
                if ($matches['default'] ?? false) {
90 29
                    return $this->buildOptionalParameterSpec($matches);
91
                }
92
93 4
                return $this->buildMandatoryParameterSpec($matches);
94 2
            } catch (ExtractorDefinitionBuilderException $e) {
95 1
                throw new ParameterSpecBuilderException("Unable to parse definition because of extractor failure: " . $e->getMessage());
96
            }
97
        }
98
99 1
        throw new ParameterSpecBuilderException("Unable to parse definition: '{$definition}'");
100
    }
101
102 2
    protected function buildVariadicParameterSpec(array $matches): VariadicParameterSpec
103
    {
104 2
        if (isset($matches['default'])) {
105 1
            throw new ParameterSpecBuilderException('Variadic parameter should have no default value');
106
        }
107
108 1
        return new VariadicParameterSpec($matches['name'], $this->builder->build($matches['type']));
109
    }
110
111 29
    protected function buildOptionalParameterSpec(array $matches): OptionalParameterSpec
112
    {
113 29
        $default = $this->buildDefaultValue($matches['default']);
114
115 29
        return new OptionalParameterSpec($matches['name'], $this->builder->build($matches['type']), $default);
116
    }
117
118 4
    protected function buildMandatoryParameterSpec(array $matches): MandatoryParameterSpec
119
    {
120 4
        return new MandatoryParameterSpec($matches['name'], $this->builder->build($matches['type']));
121
    }
122
123 29
    protected function buildDefaultValue(string $definition)
124
    {
125 29
        if (is_numeric($definition)) {
126 4
            if (false !== strpos($definition, '.')) {
127 2
                return (float)$definition;
128
            }
129
130 2
            return (int)$definition;
131
        }
132
133 25
        switch (strtolower($definition)) {
134
            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...
135 3
                return null;
136
            case 'true':
137 3
                return true;
138
            case 'false':
139 3
                return false;
140
        }
141
142
        // after this point all expected definition values MUST be at least 2 chars length
143
144 16
        if (strlen($definition) < 2) {
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 View Code Duplication
        if ('"' == $definition[0] && '"' == $definition[-1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154 7
            return trim($definition, '"');
155
        }
156 7 View Code Duplication
        if ("'" == $definition[0] && "'" == $definition[-1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157 7
            return trim($definition, "'");
158
        }
159
160
        // Less likely we will ever get here because it should fail at a parsing step, but just in case
161
        throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
162
    }
163
}
164