Completed
Pull Request — master (#90)
by Jonathan
02:28
created

RulesetInflector   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
B inflect() 0 22 5
A addRules() 0 3 1
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Inflector;
6
7
use Doctrine\Inflector\Rules\Ruleset;
8
use function array_keys;
9
use function implode;
10
use function preg_match;
11
use function preg_replace;
12
use function strtolower;
13
use function substr;
14
15
class RulesetInflector
16
{
17
    /** @var Ruleset */
18
    private $ruleset;
19
20 526
    public function __construct(Ruleset $ruleset)
21
    {
22 526
        $this->ruleset = $ruleset;
23 526
    }
24
25
    /**
26
     * @param mixed[] $rules
27
     */
28 4
    public function addRules(array $rules) : void
29
    {
30 4
        $this->ruleset->addRules($rules);
31 4
    }
32
33 510
    public function inflect(string $word) : string
34
    {
35 510
        $irregular      = $this->ruleset->getIrregular();
36 510
        $irregularRegex = '(?:' . implode('|', array_keys($irregular)) . ')';
37
38 510
        if (preg_match('/(.*)\\b(' . $irregularRegex . ')$/i', $word, $regs)) {
39 93
            return $regs[1] . $word[0] . substr($irregular[strtolower($regs[2])], 1);
40
        }
41
42 420
        $uninflectedRegex = '(?:' . implode('|', $this->ruleset->getUninflected()) . ')';
43
44 420
        if (preg_match('/^(' . $uninflectedRegex . ')$/i', $word, $regs)) {
45 244
            return $word;
46
        }
47
48 179
        foreach ($this->ruleset->getRules() as $rule => $replacement) {
49 179
            if (preg_match($rule, $word)) {
50 179
                return preg_replace($rule, $replacement, $word);
51
            }
52
        }
53
54 2
        return $word;
55
    }
56
}
57