Completed
Pull Request — master (#90)
by Jonathan
04:27
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 Doctrine\Inflector\WordInflector;
8
use function array_keys;
9
use function array_values;
10
use function implode;
11
use function preg_match;
12
use function strtolower;
13
use function substr;
14
15
class Irregular implements WordInflector
16
{
17
    /** @var Rule[] */
18
    private $rules;
19
20
    /** @var string|null */
21
    private $regex;
22
23 532
    public function __construct(Rule ...$rules)
24
    {
25 532
        foreach ($rules as $rule) {
26 532
            $this->rules[$rule->getFrom()] = $rule;
27
        }
28 532
    }
29
30
    /**
31
     * @return Rule[]
32
     */
33 530
    public function getFlippedRules() : iterable
34
    {
35 530
        foreach ($this->rules as $rule) {
36 530
            yield new Rule($rule->getTo(), $rule->getFrom());
37
        }
38 530
    }
39
40
    /**
41
     * @return Rule[]
42
     */
43 530
    public function getRules() : iterable
44
    {
45 530
        yield from array_values($this->rules);
46 530
    }
47
48 514
    public function inflect(string $word) : string
49
    {
50 514
        if (preg_match('/(.*)\\b(' . $this->getRegex() . ')$/i', $word, $regs)) {
51 94
            return $regs[1] . $word[0] . substr($this->rules[strtolower($regs[2])]->getTo(), 1);
52
        }
53
54 423
        return $word;
55
    }
56
57 514
    private function getRegex() : string
58
    {
59 514
        if ($this->regex === null) {
60 514
            $this->regex = '(?:' . implode('|', array_keys($this->rules)) . ')';
61
        }
62
63 514
        return $this->regex;
64
    }
65
}
66