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

Substitutions::getFlippedSubstitutions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
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 implode;
10
use function preg_match;
11
use function strtolower;
12
use function substr;
13
14
class Substitutions implements WordInflector
15
{
16
    /** @var Substitution[] */
17
    private $substitutions;
18
19
    /** @var string|null */
20
    private $regex;
21
22 531
    public function __construct(Substitution ...$substitutions)
23
    {
24 531
        foreach ($substitutions as $substitution) {
25 531
            $this->substitutions[$substitution->getFrom()->getWord()] = $substitution;
26
        }
27 531
    }
28
29 525
    public function getFlippedSubstitutions() : Substitutions
30
    {
31 525
        $substitutions = [];
32
33 525
        foreach ($this->substitutions as $substitution) {
34 525
            $substitutions[] = new Substitution(
35 525
                $substitution->getTo(),
36 525
                $substitution->getFrom()
37
            );
38
        }
39
40 525
        return new Substitutions(...$substitutions);
41
    }
42
43
44 272
    public function inflect(string $word) : string
45
    {
46 272
        if (preg_match('/(.*)\\b(' . $this->getRegex() . ')$/i', $word, $regs) === 1) {
47 109
            return $regs[1] . $word[0] . substr($this->substitutions[strtolower($regs[2])]->getTo()->getWord(), 1);
48
        }
49
50 168
        return $word;
51
    }
52
53 272
    private function getRegex() : string
54
    {
55 272
        if ($this->regex === null) {
56 272
            $this->regex = '(?:' . implode('|', array_keys($this->substitutions)) . ')';
57
        }
58
59 272
        return $this->regex;
60
    }
61
}
62