Completed
Pull Request — master (#3)
by Andre
06:23
created

InitialMapper::isInitial()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php
2
3
namespace TheIconic\NameParser\Mapper;
4
5
use TheIconic\NameParser\Part\AbstractPart;
6
use TheIconic\NameParser\Part\Initial;
7
8
/**
9
 * single letter, possibly followed by a period
10
 */
11
class InitialMapper extends AbstractMapper
12
{
13
    protected $matchLastPart = false;
14
15
    public function __construct(bool $matchLastPart = false)
16
    {
17
        $this->matchLastPart = $matchLastPart;
18
    }
19
20
    /**
21
     * map intials in 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
        $last = count($parts) - 1;
29
30
        foreach ($parts as $k => $part) {
31
            if ($part instanceof AbstractPart) {
32
                continue;
33
            }
34
35
            if (!$this->matchLastPart && $k === $last) {
36
                continue;
37
            }
38
39
            if ($this->isInitial($part)) {
40
                $parts[$k] = new Initial($part);
41
            }
42
        }
43
44
        return $parts;
45
    }
46
47
    /**
48
     * @param string $part
49
     * @return bool
50
     */
51
    protected function isInitial(string $part): bool
52
    {
53
        $length = strlen($part);
54
55
        if (1 === $length) {
56
            return true;
57
        }
58
59
        return ($length === 2 && substr($part, -1) ===  '.');
60
    }
61
}
62