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

Substitutions   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A getRegex() 0 7 2
A getFlippedSubstitutions() 0 12 2
A inflect() 0 7 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