Completed
Push — master ( 09801d...b7f648 )
by Andre
01:52
created

FirstnameMapper::findFirstnamePosition()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 4
nop 1
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\Initial;
9
use TheIconic\NameParser\Part\Salutation;
10
11
class FirstnameMapper extends AbstractMapper
12
{
13
    /**
14
     * map firstnames in parts array
15
     *
16
     * @param array $parts the parts
17
     * @return array the mapped parts
18
     */
19
    public function map(array $parts)
20
    {
21
        if (count($parts) < 2) {
22
            return [$this->handleSinglePart($parts[0])];
23
        }
24
25
        $pos = $this->findFirstnamePosition($parts);
26
27
        if (null !== $pos) {
28
            $parts[$pos] = new Firstname($parts[$pos]);
29
        }
30
31
        return $parts;
32
    }
33
34
    /**
35
     * @param $part
36
     * @return Firstname
37
     */
38
    protected function handleSinglePart($part)
39
    {
40
        if ($part instanceof AbstractPart) {
41
            return $part;
42
        }
43
44
        return new Firstname($part);
45
    }
46
47
    /**
48
     * @param array $parts
49
     * @return int|null
50
     */
51
    protected function findFirstnamePosition(array $parts)
52
    {
53
        $pos = null;
54
55
        $length = count($parts);
56
        $start = $this->getStartIndex($parts);
57
58
        for ($k = $start; $k < $length; $k++) {
59
            $part = $parts[$k];
60
61
            if ($part instanceof Lastname) {
62
                break;
63
            }
64
65
            if ($part instanceof Initial && null === $pos) {
66
                $pos = $k;
67
            }
68
69
            if ($part instanceof AbstractPart) {
70
                continue;
71
            }
72
73
            return $k;
74
        }
75
76
        return $pos;
77
    }
78
79
    /**
80
     * @param array $parts
81
     * @return int
82
     */
83
    protected function getStartIndex(array $parts)
84
    {
85
        $index = $this->findFirstMapped(Salutation::class, $parts);
86
87
        if (false === $index) {
88
            return 0;
89
        }
90
91
        return $index + 1;
92
    }
93
}
94