SuffixMapper::isSuffix()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace TheIconic\NameParser\Mapper;
4
5
use TheIconic\NameParser\Part\AbstractPart;
6
use TheIconic\NameParser\Part\Suffix;
7
8
class SuffixMapper extends AbstractMapper
9
{
10
    protected $suffixes = [];
11
12
    protected $matchSinglePart = false;
13
14
    protected $reservedParts = 2;
15
16
    public function __construct(array $suffixes, bool $matchSinglePart = false, int $reservedParts = 2)
17
    {
18
        $this->suffixes = $suffixes;
19
        $this->matchSinglePart = $matchSinglePart;
20
        $this->reservedParts = $reservedParts;
21
    }
22
23
    /**
24
     * map suffixes in the parts array
25
     *
26
     * @param array $parts the name parts
27
     * @return array the mapped parts
28
     */
29
    public function map(array $parts): array
30
    {
31
        if ($this->isMatchingSinglePart($parts)) {
32
            $parts[0] = new Suffix($parts[0], $this->suffixes[$this->getKey($parts[0])]);
33
            return $parts;
34
        }
35
36
        $start = count($parts) - 1;
37
38
        for ($k = $start; $k > $this->reservedParts - 1; $k--) {
39
            $part = $parts[$k];
40
41
            if (!$this->isSuffix($part)) {
42
                break;
43
            }
44
45
            $parts[$k] = new Suffix($part, $this->suffixes[$this->getKey($part)]);
46
        }
47
48
        return $parts;
49
    }
50
51
    /**
52
     * @param $parts
53
     * @return bool
54
     */
55
    protected function isMatchingSinglePart($parts): bool
56
    {
57
        if (!$this->matchSinglePart) {
58
            return false;
59
        }
60
61
        if (1 !== count($parts)) {
62
            return false;
63
        }
64
65
        return $this->isSuffix($parts[0]);
66
    }
67
68
    /**
69
     * @param $part
70
     * @return bool
71
     */
72
    protected function isSuffix($part): bool
73
    {
74
        if ($part instanceof AbstractPart) {
75
            return false;
76
        }
77
78
        return (array_key_exists($this->getKey($part), $this->suffixes));
79
    }
80
}
81