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