-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathMemoizedCombinedRegexp.php
75 lines (60 loc) · 1.89 KB
/
MemoizedCombinedRegexp.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
<?php
declare(strict_types=1);
namespace Yiisoft\Strings;
/**
* `MemoizedCombinedRegexp` is a decorator for {@see AbstractCombinedRegexp} that caches results of
* - {@see AbstractCombinedRegexp::matches()}
* - {@see AbstractCombinedRegexp::getMatchingPattern()}
* - {@see AbstractCombinedRegexp::getMatchingPatternPosition()}.
*/
final class MemoizedCombinedRegexp extends AbstractCombinedRegexp
{
/**
* @var array<string, array{matches:bool, position?:int}>
*/
private array $results = [];
public function __construct(
private AbstractCombinedRegexp $decorated,
) {
}
public function getCompiledPattern(): string
{
return $this->decorated->getCompiledPattern();
}
public function matches(string $string): bool
{
$this->evaluate($string);
return $this->results[$string]['matches'];
}
public function getMatchingPattern(string $string): string
{
$this->evaluate($string);
return $this->getPatterns()[$this->getMatchingPatternPosition($string)];
}
public function getMatchingPatternPosition(string $string): int
{
$this->evaluate($string);
return $this->results[$string]['position'] ?? $this->throwFailedMatchException($string);
}
private function evaluate(string $string): void
{
if (isset($this->results[$string])) {
return;
}
try {
$position = $this->decorated->getMatchingPatternPosition($string);
$this->results[$string]['matches'] = true;
$this->results[$string]['position'] = $position;
} catch (\Exception) {
$this->results[$string]['matches'] = false;
}
}
public function getPatterns(): array
{
return $this->decorated->getPatterns();
}
public function getFlags(): string
{
return $this->decorated->getFlags();
}
}