Passed
Pull Request — master (#90)
by Jonathan
02:20
created

Irregular::getRegex()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Inflector\Rules;
6
7
use function array_keys;
8
use function array_values;
9
use function implode;
10
use function preg_match;
11
use function strtolower;
12
use function substr;
13
14
class Irregular
15
{
16
    /** @var Rule[] */
17
    private $rules;
18
19
    /** @var string|null */
20
    private $regex;
21
22 527
    public function __construct(Rule ...$rules)
23
    {
24 527
        foreach ($rules as $rule) {
25 527
            $this->rules[$rule->getFrom()] = $rule;
26
        }
27 527
    }
28
29
    /**
30
     * @return Rule[]
31
     */
32 527
    public function getFlippedRules() : array
33
    {
34 527
        $flipped = [];
35
36 527
        foreach ($this->rules as $rule) {
37 527
            $flipped[] = new Rule($rule->getTo(), $rule->getFrom());
38
        }
39
40 527
        return $flipped;
41
    }
42
43
    /**
44
     * @return Rule[]
45
     */
46 527
    public function getRules() : array
47
    {
48 527
        return array_values($this->rules);
49
    }
50
51 511
    public function inflect(string $word) : ?string
52
    {
53 511
        if (preg_match('/(.*)\\b(' . $this->getRegex() . ')$/i', $word, $regs)) {
54 92
            return $regs[1] . $word[0] . substr($this->rules[strtolower($regs[2])]->getTo(), 1);
55
        }
56
57 421
        return null;
58
    }
59
60 511
    private function getRegex() : string
61
    {
62 511
        if ($this->regex === null) {
63 511
            $this->regex = '(?:' . implode('|', array_keys($this->rules)) . ')';
64
        }
65
66 511
        return $this->regex;
67
    }
68
}
69