1+ <?php
2+
3+ namespace HeimrichHannot \SalutationCreator \Parser \Name ;
4+
5+ use HeimrichHannot \SalutationCreator \Context \Name \AbstractName ;
6+ use HeimrichHannot \SalutationCreator \Parser \Name \Rule \Result ;
7+
8+ class StringParser extends AbstractParser
9+ {
10+ public static function defaultRules (string $ format ): array
11+ {
12+ return [];
13+ }
14+
15+ /**
16+ * @todo Refactor this method to rule based parsing
17+ */
18+ public function parse (string $ name ): ?AbstractName
19+ {
20+ $ name = preg_replace ('/\s+/u ' , ' ' , trim ($ name ));
21+ if (empty ($ name )) {
22+ return null ;
23+ }
24+
25+ if (str_contains ($ name , ', ' )) {
26+ [$ lastName , $ firstName ] = array_map ('trim ' , explode (', ' , $ name , 2 ));
27+ return $ this ->buildNameFromResult (new Result (true , $ firstName , $ lastName ));
28+ }
29+
30+ $ parts = preg_split ('/\s+/u ' , $ name , -1 , PREG_SPLIT_NO_EMPTY );
31+ $ count = count ($ parts );
32+
33+ if ($ count === 1 ) {
34+ return $ this ->buildNameFromResult (new Result (true , '' , $ parts [0 ]));
35+ }
36+
37+ if ($ count === 2 ) {
38+ return $ this ->buildNameFromResult (new Result (true , $ parts [0 ], $ parts [1 ]));
39+ }
40+
41+ $ surnamePrefixes = [
42+ 'von ' ,
43+ 'vom ' ,
44+ 'van ' ,
45+ 'de ' ,
46+ 'del ' ,
47+ 'della ' ,
48+ 'der ' ,
49+ 'den ' ,
50+ 'zu ' ,
51+ 'zur ' ,
52+ 'zum ' ,
53+ 'da ' ,
54+ 'di ' ,
55+ 'du ' ,
56+ 'la ' ,
57+ 'le ' ,
58+ 'dos ' ,
59+ 'das ' ,
60+ 'do ' ,
61+ 'bin ' ,
62+ 'al ' ,
63+ ];
64+
65+ // Startpunkt des Nachnamens suchen
66+ $ lastNameStartIndex = $ count - 1 ;
67+
68+ while (
69+ $ lastNameStartIndex > 0
70+ && in_array (mb_strtolower ($ parts [$ lastNameStartIndex - 1 ]), $ surnamePrefixes , true )
71+ ) {
72+ $ lastNameStartIndex --;
73+ }
74+
75+ if ($ lastNameStartIndex < $ count - 1 ) {
76+ return $ this ->buildNameFromResult (
77+ new Result (
78+ true ,
79+ implode (' ' , array_slice ($ parts , 0 , $ lastNameStartIndex )),
80+ implode (' ' , array_slice ($ parts , $ lastNameStartIndex )),
81+ )
82+ );
83+ }
84+
85+ // at least we have only wild guessing :)
86+ $ splitIndex = (int ) ceil ($ count / 2 );
87+ return $ this ->buildNameFromResult (
88+ new Result (
89+ true ,
90+ implode (' ' , array_slice ($ parts , 0 , $ splitIndex )),
91+ implode (' ' , array_slice ($ parts , $ splitIndex ))
92+ )
93+ );
94+ }
95+ }
0 commit comments