|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TheIconic\NameParser\Mapper; |
|
4
|
|
|
|
|
5
|
|
|
use TheIconic\NameParser\Part\AbstractPart; |
|
6
|
|
|
use TheIconic\NameParser\Part\Initial; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* single letter, possibly followed by a period |
|
10
|
|
|
*/ |
|
11
|
|
|
class InitialMapper extends AbstractMapper |
|
12
|
|
|
{ |
|
13
|
|
|
protected $matchLastPart = false; |
|
14
|
|
|
|
|
15
|
|
|
private $combinedMax = 2; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct(int $combinedMax = 2, bool $matchLastPart = false) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->matchLastPart = $matchLastPart; |
|
20
|
|
|
$this->combinedMax = $combinedMax; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* map intials in 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
|
|
|
$last = count($parts) - 1; |
|
32
|
|
|
|
|
33
|
|
|
for ($k = 0; $k < count($parts); $k++) { |
|
|
|
|
|
|
34
|
|
|
$part = $parts[$k]; |
|
35
|
|
|
|
|
36
|
|
|
if ($part instanceof AbstractPart) { |
|
37
|
|
|
continue; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
if (!$this->matchLastPart && $k === $last) { |
|
41
|
|
|
continue; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (strtoupper($part) === $part) { |
|
45
|
|
|
$stripped = str_replace('.', '', $part); |
|
46
|
|
|
$length = strlen($stripped); |
|
47
|
|
|
|
|
48
|
|
|
if (1 < $length && $length <= $this->combinedMax) { |
|
49
|
|
|
array_splice($parts, $k, 1, str_split($stripped)); |
|
50
|
|
|
$last = count($parts) - 1; |
|
51
|
|
|
$part = $parts[$k]; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
if ($this->isInitial($part)) { |
|
56
|
|
|
$parts[$k] = new Initial($part); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $parts; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param string $part |
|
65
|
|
|
* @return bool |
|
66
|
|
|
*/ |
|
67
|
|
|
protected function isInitial(string $part): bool |
|
68
|
|
|
{ |
|
69
|
|
|
$length = strlen($part); |
|
70
|
|
|
|
|
71
|
|
|
if (1 === $length) { |
|
72
|
|
|
return true; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return ($length === 2 && substr($part, -1) === '.'); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: