1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TheIconic\NameParser\Mapper; |
4
|
|
|
|
5
|
|
|
use TheIconic\NameParser\Part\AbstractPart; |
6
|
|
|
use TheIconic\NameParser\Part\Nickname; |
7
|
|
|
|
8
|
|
|
class NicknameMapper extends AbstractMapper |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var array |
12
|
|
|
*/ |
13
|
|
|
protected $delimiters = [ |
14
|
|
|
'[' => ']', |
15
|
|
|
'{' => '}', |
16
|
|
|
'(' => ')', |
17
|
|
|
'<' => '>', |
18
|
|
|
'"' => '"', |
19
|
|
|
'\'' => '\'' |
20
|
|
|
]; |
21
|
|
|
|
22
|
|
|
public function __construct(array $delimiters = []) |
23
|
|
|
{ |
24
|
|
|
if (!empty($delimiters)) { |
25
|
|
|
$this->delimiters = $delimiters; |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* map nicknames in the parts array |
31
|
|
|
* |
32
|
|
|
* @param array $parts the name parts |
33
|
|
|
* @return array the mapped parts |
34
|
|
|
*/ |
35
|
|
|
public function map(array $parts): array |
36
|
|
|
{ |
37
|
|
|
$isEncapsulated = false; |
38
|
|
|
|
39
|
|
|
$regexp = $this->buildRegexp(); |
40
|
|
|
|
41
|
|
|
$closingDelimiter = ''; |
42
|
|
|
|
43
|
|
|
foreach ($parts as $k => $part) { |
44
|
|
|
if ($part instanceof AbstractPart) { |
45
|
|
|
continue; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (preg_match($regexp, $part, $matches)) { |
49
|
|
|
$isEncapsulated = true; |
50
|
|
|
$part = substr($part, 1); |
51
|
|
|
$closingDelimiter = $this->delimiters[$matches[1]]; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (!$isEncapsulated) { |
55
|
|
|
continue; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if ($closingDelimiter === substr($part, -1)) { |
59
|
|
|
$isEncapsulated = false; |
60
|
|
|
$part = substr($part, 0, -1); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$parts[$k] = new Nickname(str_replace(['"', '\''], '', $part)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $parts; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
|
|
protected function buildRegexp() |
73
|
|
|
{ |
74
|
|
|
$regexp = '/^(['; |
75
|
|
|
|
76
|
|
|
foreach ($this->delimiters as $opening => $closing) { |
77
|
|
|
$regexp .= sprintf('\\%s', $opening); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
$regexp .= '])/'; |
81
|
|
|
|
82
|
|
|
return $regexp; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|