1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TheIconic\NameParser\Mapper; |
4
|
|
|
|
5
|
|
|
use TheIconic\NameParser\Part\AbstractPart; |
6
|
|
|
use TheIconic\NameParser\Part\Nickname; |
7
|
|
|
|
8
|
|
|
abstract class AbstractMapper |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* implements the mapping of parts |
12
|
|
|
* |
13
|
|
|
* @param array $parts - the name parts |
14
|
|
|
* @return array $parts - the mapped parts |
15
|
|
|
*/ |
16
|
|
|
abstract public function map(array $parts); |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* checks if there are still unmapped parts left before the given position |
20
|
|
|
* |
21
|
|
|
* @param array $parts |
22
|
|
|
* @param int $index |
23
|
|
|
* @return bool |
24
|
|
|
*/ |
25
|
|
|
protected function hasUnmappedPartsBefore(array $parts, $index): bool |
26
|
|
|
{ |
27
|
|
|
foreach ($parts as $k => $part) { |
28
|
|
|
if ($k === $index) { |
29
|
|
|
break; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (!($part instanceof AbstractPart)) { |
33
|
|
|
return true; |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param string $type |
42
|
|
|
* @param array $parts |
43
|
|
|
* @return int|bool |
44
|
|
|
*/ |
45
|
|
|
protected function findFirstMapped(string $type, array $parts) |
46
|
|
|
{ |
47
|
|
|
$total = count($parts); |
48
|
|
|
|
49
|
|
|
for ($i = 0; $i < $total; $i++) { |
50
|
|
|
if ($parts[$i] instanceof $type) { |
51
|
|
|
return $i; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* get the registry lookup key for the given word |
60
|
|
|
* |
61
|
|
|
* @param string $word the word |
62
|
|
|
* @return string the key |
63
|
|
|
*/ |
64
|
|
|
protected function getKey($word): string |
65
|
|
|
{ |
66
|
|
|
return strtolower(str_replace('.', '', $word)); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* sort array by length descending and alphabetically ascending |
71
|
|
|
* https://stackoverflow.com/questions/44835807/sort-array-by-length-and-then-alphabetically |
72
|
|
|
* |
73
|
|
|
* @param array $values |
74
|
|
|
* @return array |
75
|
|
|
*/ |
76
|
|
|
protected function sortArrayDescending(array $values): array |
77
|
|
|
{ |
78
|
|
|
uasort($values, function($a, $b) { |
79
|
|
|
return strlen($b) <=> strlen($a) ?: strcmp($a, $b);; |
80
|
|
|
}); |
81
|
|
|
|
82
|
|
|
return $values; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
|