Completed
Push — master ( 0c176f...c02018 )
by Bogdan
05:40
created

ParameterSpecBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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>
60
                ((?:((\w+\b(?:\(.*\))?(?:\s*\[\s*\])?)(?:\s*\|\s*(?-2))*))|(?:\(\s*(?-3)\s*\)(?:\s*\[\s*\])?)|(\[\s*\]))
61
            )
62
            \s*
63
        )?
64
        $
65
        /xi';
66
    /**
67
     * @var ExtractorDefinitionBuilderInterface
68
     */
69
    private $builder;
70
71 39
    public function __construct(ExtractorDefinitionBuilderInterface $builder)
72
    {
73 39
        $this->builder = $builder;
74 39
    }
75
76
    /**
77
     * @param string $definition
78
     *
79
     * @return ParameterSpecInterface
80
     * @throws ParameterSpecBuilderException
81
     */
82 39
    public function build(string $definition): ParameterSpecInterface
83
    {
84 39
        $definition = trim($definition);
85
86 39
        if (!$definition) {
87 1
            throw new ParameterSpecBuilderException('Definition must be non-empty string');
88
        }
89
90 38
        if (preg_match($this->regexp, $definition, $matches)) {
91
            try {
92 37
                if ($matches['rest'] ?? false) {
93 2
                    return $this->buildVariadicParameterSpec($matches);
94
                }
95
96 35
                if ($matches['default'] ?? false) {
97 31
                    return $this->buildOptionalParameterSpec($matches);
98
                }
99
100 4
                return $this->buildMandatoryParameterSpec($matches);
101 2
            } catch (ExtractorDefinitionBuilderException $e) {
102 1
                throw new ParameterSpecBuilderException("Unable to parse definition because of extractor failure: " . $e->getMessage());
103
            }
104
        }
105
106 1
        throw new ParameterSpecBuilderException("Unable to parse definition: '{$definition}'");
107
    }
108
109 2
    protected function buildVariadicParameterSpec(array $matches): VariadicParameterSpec
110
    {
111 2
        if (isset($matches['default']) && '' !== $matches['default']) {
112 1
            throw new ParameterSpecBuilderException('Variadic parameter should have no default value');
113
        }
114
115 1
        return new VariadicParameterSpec($matches['name'], $this->builder->build($matches['type']));
116
    }
117
118 31
    protected function buildOptionalParameterSpec(array $matches): OptionalParameterSpec
119
    {
120 31
        $default = $this->buildDefaultValue($matches['default']);
121
122 31
        return new OptionalParameterSpec($matches['name'], $this->builder->build($matches['type']), $default);
123
    }
124
125 4
    protected function buildMandatoryParameterSpec(array $matches): MandatoryParameterSpec
126
    {
127 4
        return new MandatoryParameterSpec($matches['name'], $this->builder->build($matches['type']));
128
    }
129
130 31
    protected function buildDefaultValue(string $definition)
131
    {
132 31
        if (is_numeric($definition)) {
133 4
            if (false !== strpos($definition, '.')) {
134 2
                return (float)$definition;
135
            }
136
137 2
            return (int)$definition;
138
        }
139
140 27
        switch (strtolower($definition)) {
141
            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...
142 3
                return null;
143
            case 'true':
144 3
                return true;
145
            case 'false':
146 3
                return false;
147
        }
148
149
        // after this point all expected definition values MUST be at least 2 chars length
150
151 18
        if (strlen($definition) < 2) {
152
            // UNEXPECTED
153
            // Less likely we will ever get here because it should fail at a parsing step, but just in case
154
            throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
155
        }
156
157 18
        if ($this->wrappedWith($definition, '[', ']')) {
158 2
            return [];
159
        }
160
161 16
        if ($this->wrappedWith($definition, '{', '}')) {
162 2
            return [];
163
        }
164
165 14
        foreach (['"', "'"] as $quote) {
166 14
            if ($this->wrappedWith($definition, $quote, $quote)) {
167 14
                return trim($definition, $quote);
168
            }
169
        }
170
171
        // Less likely we will ever get here because it should fail at a parsing step, but just in case
172
        throw new ParameterSpecBuilderException("Unknown default value format '{$definition}'");
173
    }
174
175 18
    private function wrappedWith(string $definition, string $starts, $ends)
176
    {
177 18
        assert(strlen($definition) >= 2);
178
179 18
        return $starts == $definition[0] && $ends == $definition[-1];
180
    }
181
}
182