1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Innmind\Immutable; |
5
|
|
|
|
6
|
|
|
use Innmind\Immutable\Exception\{ |
7
|
|
|
LogicException, |
8
|
|
|
InvalidRegex, |
9
|
|
|
}; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @psalm-immutable |
13
|
|
|
*/ |
14
|
|
|
final class RegExp |
15
|
10 |
|
{ |
16
|
|
|
private string $pattern; |
17
|
10 |
|
|
18
|
1 |
|
private function __construct(string $pattern) |
19
|
|
|
{ |
20
|
|
|
if (@\preg_match($pattern, '') === false) { |
21
|
9 |
|
/** @psalm-suppress ImpureFunctionCall */ |
22
|
9 |
|
throw new LogicException($pattern, \preg_last_error()); |
23
|
|
|
} |
24
|
6 |
|
|
25
|
|
|
$this->pattern = $pattern; |
26
|
6 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @psalm-pure |
30
|
|
|
*/ |
31
|
|
|
public static function of(string $pattern): self |
32
|
3 |
|
{ |
33
|
|
|
return new self($pattern); |
34
|
3 |
|
} |
35
|
|
|
|
36
|
3 |
|
/** |
37
|
1 |
|
* @throws InvalidRegex |
38
|
|
|
*/ |
39
|
|
|
public function matches(Str $string): bool |
40
|
2 |
|
{ |
41
|
|
|
$value = \preg_match($this->pattern, $string->toString()); |
42
|
|
|
|
43
|
|
|
if ($value === false) { |
44
|
|
|
/** @psalm-suppress ImpureFunctionCall */ |
45
|
|
|
throw new InvalidRegex('', \preg_last_error()); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return (bool) $value; |
49
|
4 |
|
} |
50
|
|
|
|
51
|
4 |
|
/** |
52
|
4 |
|
* @throws InvalidRegex |
53
|
|
|
* |
54
|
4 |
|
* @return Map<int|string, Str> |
55
|
1 |
|
*/ |
56
|
|
|
public function capture(Str $string): Map |
57
|
|
|
{ |
58
|
|
|
$matches = []; |
59
|
3 |
|
$value = \preg_match($this->pattern, $string->toString(), $matches); |
60
|
|
|
|
61
|
3 |
|
if ($value === false) { |
62
|
3 |
|
/** @psalm-suppress ImpureFunctionCall */ |
63
|
3 |
|
throw new InvalidRegex('', \preg_last_error()); |
64
|
|
|
} |
65
|
3 |
|
|
66
|
3 |
|
/** @var Map<int|string, Str> */ |
67
|
|
|
$map = Map::of(); |
68
|
|
|
|
69
|
|
|
foreach ($matches as $key => $match) { |
70
|
|
|
/** @psalm-suppress RedundantCast Don't trust the types of preg_match */ |
71
|
3 |
|
$map = ($map)( |
72
|
|
|
$key, |
73
|
|
|
Str::of( |
74
|
2 |
|
(string) $match, |
75
|
|
|
$string->encoding()->toString(), |
76
|
2 |
|
), |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $map; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function toString(): string |
84
|
|
|
{ |
85
|
|
|
return $this->pattern; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|