1 | <?php |
||
9 | class LastnameMapper extends AbstractMapper |
||
10 | { |
||
11 | /** |
||
12 | * @var array options |
||
13 | */ |
||
14 | protected $options = [ |
||
15 | 'match_single' => false, |
||
16 | ]; |
||
17 | |||
18 | /** |
||
19 | * map lastnames in the parts array |
||
20 | * |
||
21 | * @param array $parts the name parts |
||
22 | * @return array the mapped parts |
||
23 | */ |
||
24 | public function map(array $parts): array |
||
25 | { |
||
26 | if (!$this->options['match_single'] && count($parts) < 2) { |
||
27 | return $parts; |
||
28 | } |
||
29 | |||
30 | $parts = array_reverse($parts); |
||
31 | |||
32 | $parts = $this->mapReversedParts($parts); |
||
33 | |||
34 | return array_reverse($parts); |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @param array $parts |
||
39 | * @return array |
||
40 | */ |
||
41 | protected function mapReversedParts(array $parts): array |
||
42 | { |
||
43 | $length = count($parts); |
||
44 | |||
45 | foreach ($parts as $k => $part) { |
||
46 | if ($part instanceof Suffix) { |
||
47 | continue; |
||
48 | } |
||
49 | |||
50 | if ($part instanceof AbstractPart) { |
||
51 | break; |
||
52 | } |
||
53 | |||
54 | $originalIndex = $length - $k - 1; |
||
55 | $originalParts = array_reverse($parts); |
||
56 | |||
57 | if ($this->isFollowedByLastnamePart($originalParts, $originalIndex)) { |
||
58 | if ($this->isApplicablePrefix($originalParts, $originalIndex)) { |
||
59 | $lastname = new Lastname($part); |
||
60 | $lastname->setApplyPrefix(true); |
||
61 | $parts[$k] = $lastname; |
||
62 | continue; |
||
63 | } |
||
64 | break; |
||
65 | } |
||
66 | |||
67 | $parts[$k] = new Lastname($part); |
||
68 | } |
||
69 | |||
70 | return $parts; |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * @param array $parts |
||
75 | * @param int $index |
||
76 | * @return bool |
||
77 | */ |
||
78 | protected function isFollowedByLastnamePart(array $parts, int $index): bool |
||
84 | |||
85 | /** |
||
86 | * Assuming that the part at the given index is matched as a prefix, |
||
87 | * determines if the prefix should be applied to the lastname. |
||
88 | * |
||
89 | * We only apply it to the lastname if we already have at least one |
||
90 | * lastname part and there are other parts left in |
||
91 | * the name (this effectively prioritises firstname over prefix matching). |
||
92 | * |
||
93 | * This expects the parts array and index to be in the original order. |
||
94 | * |
||
95 | * @param array $parts |
||
96 | * @param int $index |
||
97 | * @return bool |
||
98 | */ |
||
99 | protected function isApplicablePrefix(array $parts, int $index): bool |
||
107 | } |
||
108 |