|
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
|
|
|
public function __construct(array $suffixes, bool $matchSinglePart = false) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->suffixes = $suffixes; |
|
17
|
|
|
$this->matchSinglePart = $matchSinglePart; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* map suffixes in the parts array |
|
22
|
|
|
* |
|
23
|
|
|
* @param array $parts the name parts |
|
24
|
|
|
* @return array the mapped parts |
|
25
|
|
|
*/ |
|
26
|
|
|
public function map(array $parts): array |
|
27
|
|
|
{ |
|
28
|
|
|
if ($this->isMatchingSinglePart($parts)) { |
|
29
|
|
|
$parts[0] = new Suffix($parts[0], $this->suffixes[$this->getKey($parts[0])]); |
|
30
|
|
|
return $parts; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$start = count($parts) - 1; |
|
34
|
|
|
|
|
35
|
|
|
for ($k = $start; $k > 1; $k--) { |
|
36
|
|
|
$part = $parts[$k]; |
|
37
|
|
|
|
|
38
|
|
|
if (!$this->isSuffix($part)) { |
|
39
|
|
|
break; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$parts[$k] = new Suffix($part, $this->suffixes[$this->getKey($part)]); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $parts; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param $parts |
|
50
|
|
|
* @return bool |
|
51
|
|
|
*/ |
|
52
|
|
|
protected function isMatchingSinglePart($parts): bool |
|
53
|
|
|
{ |
|
54
|
|
|
if (!$this->matchSinglePart) { |
|
55
|
|
|
return false; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if (1 !== count($parts)) { |
|
59
|
|
|
return false; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return $this->isSuffix($parts[0]); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param $part |
|
67
|
|
|
* @return bool |
|
68
|
|
|
*/ |
|
69
|
|
|
protected function isSuffix($part): bool |
|
70
|
|
|
{ |
|
71
|
|
|
if ($part instanceof AbstractPart) { |
|
72
|
|
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return (array_key_exists($this->getKey($part), $this->suffixes)); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|