Passed
Pull Request — master (#97)
by Jonathan
02:15
created

Irregular::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
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 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 Substitution[] */
18
    private $substitutions;
19
20
    /** @var string|null */
21
    private $regex;
22
23 532
    public function __construct(Substitution ...$substitutions)
24
    {
25 532
        foreach ($substitutions as $substitution) {
26 532
            $this->substitutions[$substitution->getFrom()->getWord()] = $substitution;
27
        }
28 532
    }
29
30
    /**
31
     * @return Substitution[]
32
     */
33 528
    public function getFlippedSubstitutions() : iterable
34
    {
35 528
        foreach ($this->substitutions as $substitution) {
36 528
            yield new Substitution($substitution->getTo(), $substitution->getFrom());
37
        }
38 528
    }
39
40
    /**
41
     * @return Substitution[]
42
     */
43 528
    public function getSubstitutions() : iterable
44
    {
45 528
        yield from array_values($this->substitutions);
46 528
    }
47
48 271
    public function inflect(string $word) : string
49
    {
50 271
        if (preg_match('/(.*)\\b(' . $this->getRegex() . ')$/i', $word, $regs) > 0) {
51 96
            return $regs[1] . $word[0] . substr($this->substitutions[strtolower($regs[2])]->getTo()->getWord(), 1);
52
        }
53
54 180
        return $word;
55
    }
56
57 271
    private function getRegex() : string
58
    {
59 271
        if ($this->regex === null) {
60 271
            $this->regex = '(?:' . implode('|', array_keys($this->substitutions)) . ')';
61
        }
62
63 271
        return $this->regex;
64
    }
65
}
66