Failed Conditions
Pull Request — master (#97)
by Jonathan
02:40
created

Irregular::getRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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