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

RulesetInflector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
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;
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