InitialMapper::map()   B
last analyzed

Complexity

Conditions 9
Paths 9

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.0555
c 0
b 0
f 0
cc 9
nc 9
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
    private $combinedMax = 2;
16
17
    public function __construct(int $combinedMax = 2, bool $matchLastPart = false)
18
    {
19
        $this->matchLastPart = $matchLastPart;
20
        $this->combinedMax = $combinedMax;
21
    }
22
23
    /**
24
     * map intials in parts array
25
     *
26
     * @param array $parts the name parts
27
     * @return array the mapped parts
28
     */
29
    public function map(array $parts): array
30
    {
31
        $last = count($parts) - 1;
32
33
        for ($k = 0; $k < count($parts); $k++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
34
            $part = $parts[$k];
35
36
            if ($part instanceof AbstractPart) {
37
                continue;
38
            }
39
40
            if (!$this->matchLastPart && $k === $last) {
41
                continue;
42
            }
43
44
            if (strtoupper($part) === $part) {
45
                $stripped = str_replace('.', '', $part);
46
                $length = strlen($stripped);
47
48
                if (1 < $length && $length <= $this->combinedMax) {
49
                    array_splice($parts, $k, 1, str_split($stripped));
50
                    $last = count($parts) - 1;
51
                    $part = $parts[$k];
52
                }
53
            }
54
55
            if ($this->isInitial($part)) {
56
                $parts[$k] = new Initial($part);
57
            }
58
        }
59
60
        return $parts;
61
    }
62
63
    /**
64
     * @param string $part
65
     * @return bool
66
     */
67
    protected function isInitial(string $part): bool
68
    {
69
        $length = strlen($part);
70
71
        if (1 === $length) {
72
            return true;
73
        }
74
75
        return ($length === 2 && substr($part, -1) ===  '.');
76
    }
77
}
78