1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TheIconic\NameParser\Mapper; |
4
|
|
|
|
5
|
|
|
use TheIconic\NameParser\Part\AbstractPart; |
6
|
|
|
use TheIconic\NameParser\Part\Firstname; |
7
|
|
|
use TheIconic\NameParser\Part\Lastname; |
8
|
|
|
use TheIconic\NameParser\Part\Middlename; |
9
|
|
|
|
10
|
|
|
class MiddlenameMapper extends AbstractMapper |
11
|
|
|
{ |
12
|
|
|
protected $mapWithoutLastname = false; |
13
|
|
|
|
14
|
|
|
public function __construct(bool $mapWithoutLastname = false) |
15
|
|
|
{ |
16
|
|
|
$this->mapWithoutLastname = $mapWithoutLastname; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* map middlenames in the parts array |
21
|
|
|
* |
22
|
|
|
* @param array $parts the name parts |
23
|
|
|
* @return array the mapped parts |
24
|
|
|
*/ |
25
|
|
|
public function map(array $parts): array |
26
|
|
|
{ |
27
|
|
|
// If we don't expect a lastname, match a mimimum of 2 parts |
28
|
|
|
$minumumParts = ($this->mapWithoutLastname ? 2 : 3); |
29
|
|
|
|
30
|
|
|
if (count($parts) < $minumumParts) { |
31
|
|
|
return $parts; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$start = $this->findFirstMapped(Firstname::class, $parts); |
35
|
|
|
|
36
|
|
|
if (false === $start) { |
37
|
|
|
return $parts; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $this->mapFrom($start, $parts); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param $start |
45
|
|
|
* @param $parts |
46
|
|
|
* @return mixed |
47
|
|
|
*/ |
48
|
|
|
protected function mapFrom($start, $parts): array |
49
|
|
|
{ |
50
|
|
|
// If we don't expect a lastname, include the last part, |
51
|
|
|
// otherwise skip the last (-1) because it should be a lastname |
52
|
|
|
$length = count($parts) - ($this->mapWithoutLastname ? 0 : 1); |
53
|
|
|
|
54
|
|
|
for ($k = $start; $k < $length; $k++) { |
55
|
|
|
$part = $parts[$k]; |
56
|
|
|
|
57
|
|
|
if ($part instanceof Lastname) { |
58
|
|
|
break; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if ($part instanceof AbstractPart) { |
62
|
|
|
continue; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$parts[$k] = new Middlename($part); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $parts; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|