Completed
Pull Request — master (#3)
by Бабичев
03:59
created

Path::processing()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 1
nop 0
dl 0
loc 22
ccs 0
cts 14
cp 0
crap 12
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\Router;
4
5
use Bavix\Exceptions\Runtime;
6
7
class Path
8
{
9
10
    /**
11
     * @var string
12
     */
13
    protected $path;
14
15
    /**
16
     * @var array
17
     */
18
    protected $regex;
19
20
    /**
21
     * Path constructor.
22
     * @param string $path
23
     * @param array $regex
24
     */
25
    public function __construct(string $path, array $regex = [])
26
    {
27
        $this->path = $path;
28
        $this->regex = $regex;
29
        $this->processing();
30
    }
31
32
    /**
33
     * @return string
34
     */
35
    public function getPattern(): string
36
    {
37
        // todo
38
    }
39
40
    /**
41
     * @return string
42
     */
43
    public function getPath(): string
44
    {
45
        return $this->path;
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getRegex(): array
52
    {
53
        return $this->regex;
54
    }
55
56
    /**
57
     * @param self $parent
58
     */
59
    public function hinge(self $parent): void
60
    {
61
        $this->path = $parent->path . $this->path;
62
        $this->regex = \array_merge(
63
            $parent->regex,
64
            $this->regex
65
        );
66
    }
67
68
    /**
69
     * processing:
70
     *  path: '/(<lang:\w+>)' -> '/(<lang>)'
71
     *  re: [] -> ['lang' => '\w+']
72
     *
73
     *  if attr exists -> throws
74
     */
75
    protected function processing(): void
76
    {
77
        $this->path = \preg_replace_callback(
78
            '~\<(?<key>\w+):(?<value>.+?)>~',
79
            function (array $matches) {
80
81
                if (!empty($this->regex[$matches['key']])) {
82
                    throw new Runtime(\sprintf(
83
                        'duplicate in registry key `%s` for path `%s`',
84
                        $matches['key'],
85
                        $this->path
86
                    ));
87
                }
88
89
                if (!empty($matches['value']))
90
                {
91
                    $this->regex[$matches['key']] = $matches['value'];
92
                }
93
94
                return '<' . $matches['key'] . '>';
95
            },
96
            $this->path
97
        );
98
    }
99
100
}
101