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

Irregular::getFlippedRules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
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 532
    public function __construct(Rule ...$rules)
23
    {
24 532
        foreach ($rules as $rule) {
25 532
            $this->rules[$rule->getFrom()] = $rule;
26
        }
27 532
    }
28
29
    /**
30
     * @return Rule[]
31
     */
32 530
    public function getFlippedRules() : iterable
33
    {
34 530
        foreach ($this->rules as $rule) {
35 530
            yield new Rule($rule->getTo(), $rule->getFrom());
36
        }
37 530
    }
38
39
    /**
40
     * @return Rule[]
41
     */
42 530
    public function getRules() : iterable
43
    {
44 530
        yield from array_values($this->rules);
45 530
    }
46
47 514
    public function inflect(string $word) : ?string
48
    {
49 514
        if (preg_match('/(.*)\\b(' . $this->getRegex() . ')$/i', $word, $regs)) {
50 94
            return $regs[1] . $word[0] . substr($this->rules[strtolower($regs[2])]->getTo(), 1);
51
        }
52
53 423
        return null;
54
    }
55
56 514
    private function getRegex() : string
57
    {
58 514
        if ($this->regex === null) {
59 514
            $this->regex = '(?:' . implode('|', array_keys($this->rules)) . ')';
60
        }
61
62 514
        return $this->regex;
63
    }
64
}
65