Total Complexity | 9 |
Total Lines | 60 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
11 | final class RegExp |
||
12 | { |
||
13 | private $pattern; |
||
14 | |||
15 | 20 | public function __construct(string $pattern) |
|
16 | { |
||
17 | 20 | if (@\preg_match($pattern, '') === false) { |
|
18 | 2 | throw new DomainException($pattern, \preg_last_error()); |
|
19 | } |
||
20 | |||
21 | 18 | $this->pattern = $pattern; |
|
22 | 18 | } |
|
23 | |||
24 | 12 | public static function of(string $pattern): self |
|
25 | { |
||
26 | 12 | return new self($pattern); |
|
27 | } |
||
28 | |||
29 | 6 | public function matches(Str $string): bool |
|
30 | { |
||
31 | 6 | $value = \preg_match($this->pattern, (string) $string); |
|
32 | |||
33 | 6 | if ($value === false) { |
|
34 | 2 | throw new RegexException('', \preg_last_error()); |
|
35 | } |
||
36 | |||
37 | 4 | return (bool) $value; |
|
38 | } |
||
39 | |||
40 | |||
41 | /** |
||
42 | * @return MapInterface<scalar, Str> |
||
43 | */ |
||
44 | 8 | public function capture(Str $string): MapInterface |
|
45 | { |
||
46 | 8 | $matches = []; |
|
47 | 8 | $value = \preg_match($this->pattern, (string) $string, $matches); |
|
48 | |||
49 | 8 | if ($value === false) { |
|
50 | 2 | throw new RegexException('', \preg_last_error()); |
|
51 | } |
||
52 | |||
53 | 6 | $map = new Map('scalar', Str::class); |
|
54 | |||
55 | 6 | foreach ($matches as $key => $match) { |
|
56 | 6 | $map = $map->put( |
|
57 | 6 | $key, |
|
58 | 6 | new Str( |
|
59 | 6 | (string) $match, |
|
60 | 6 | (string) $string->encoding() |
|
61 | ) |
||
62 | ); |
||
63 | } |
||
64 | |||
65 | 6 | return $map; |
|
66 | } |
||
67 | |||
68 | 4 | public function __toString(): string |
|
71 | } |
||
72 | } |
||
73 |