MemoizedCombinedRegexp::getCompiledPattern()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Strings;
6
7
/**
8
 * `MemoizedCombinedRegexp` is a decorator for {@see AbstractCombinedRegexp} that caches results of
9
 * - {@see AbstractCombinedRegexp::matches()}
10
 * - {@see AbstractCombinedRegexp::getMatchingPattern()}
11
 * - {@see AbstractCombinedRegexp::getMatchingPatternPosition()}.
12
 */
13
final class MemoizedCombinedRegexp extends AbstractCombinedRegexp
14
{
15
    /**
16
     * @var array<string, array{matches:bool, position?:int}>
17
     */
18
    private array $results = [];
19
20 20
    public function __construct(
21
        private AbstractCombinedRegexp $decorated,
22
    ) {
23 20
    }
24
25 18
    public function getCompiledPattern(): string
26
    {
27 18
        return $this->decorated->getCompiledPattern();
28
    }
29
30 13
    public function matches(string $string): bool
31
    {
32 13
        $this->evaluate($string);
33
34 13
        return $this->results[$string]['matches'];
35
    }
36
37 6
    public function getMatchingPattern(string $string): string
38
    {
39 6
        $this->evaluate($string);
40
41 6
        return $this->getPatterns()[$this->getMatchingPatternPosition($string)];
42
    }
43
44 10
    public function getMatchingPatternPosition(string $string): int
45
    {
46 10
        $this->evaluate($string);
47
48 10
        return $this->results[$string]['position'] ?? $this->throwFailedMatchException($string);
49
    }
50
51 19
    private function evaluate(string $string): void
52
    {
53 19
        if (isset($this->results[$string])) {
54 7
            return;
55
        }
56
        try {
57 19
            $position = $this->decorated->getMatchingPatternPosition($string);
58
59 17
            $this->results[$string]['matches'] = true;
60 17
            $this->results[$string]['position'] = $position;
61 2
        } catch (\Exception) {
62 2
            $this->results[$string]['matches'] = false;
63
        }
64
    }
65
66 6
    public function getPatterns(): array
67
    {
68 6
        return $this->decorated->getPatterns();
69
    }
70
71 1
    public function getFlags(): string
72
    {
73 1
        return $this->decorated->getFlags();
74
    }
75
}
76