|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TheIconic\NameParser\Mapper; |
|
4
|
|
|
|
|
5
|
|
|
use TheIconic\NameParser\Part\AbstractPart; |
|
6
|
|
|
use TheIconic\NameParser\Part\Salutation; |
|
7
|
|
|
|
|
8
|
|
|
class SalutationMapper extends AbstractMapper |
|
9
|
|
|
{ |
|
10
|
|
|
protected $salutations = []; |
|
11
|
|
|
|
|
12
|
|
|
protected $maxIndex = 0; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(array $salutations, $maxIndex = 0) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->salutations = $salutations; |
|
17
|
|
|
$this->maxIndex = $maxIndex; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* map salutations 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
|
|
|
$max = ($this->maxIndex > 0) ? $this->maxIndex : floor(count($parts) / 2); |
|
29
|
|
|
|
|
30
|
|
|
for ($k = 0; $k < $max; $k++) { |
|
31
|
|
|
if ($parts[$k] instanceof AbstractPart) { |
|
32
|
|
|
break; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
$parts = $this->substituteWithSalutation($parts, $k); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
return $parts; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
protected function substituteWithSalutation(array $parts, int $start): array |
|
42
|
|
|
{ |
|
43
|
|
|
foreach ($this->salutations as $key => $salutation) { |
|
44
|
|
|
$keys = explode(' ', $key); |
|
45
|
|
|
$length = count($keys); |
|
46
|
|
|
|
|
47
|
|
|
$subset = array_slice($parts, $start, $length); |
|
48
|
|
|
|
|
49
|
|
|
if ($this->isMatchingSubset($keys, $subset)) { |
|
50
|
|
|
array_splice($parts, $start, $length, [new Salutation(implode(' ', $subset), $salutation)]); |
|
51
|
|
|
return $parts; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $parts; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function isMatchingSubset(array $keys, array $subset): bool |
|
59
|
|
|
{ |
|
60
|
|
|
for ($i = 0; $i < count($subset); $i++) { |
|
|
|
|
|
|
61
|
|
|
if ($this->getKey($subset[$i]) !== $keys[$i]) { |
|
62
|
|
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return true; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
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: