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

Irregular   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A getFlippedRules() 0 4 2
A getRules() 0 3 1
A getRegex() 0 7 2
A inflect() 0 7 2
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