Completed
Pull Request — master (#29)
by Andre
01:07
created

SalutationMapper::isMatchingSubset()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace TheIconic\NameParser\Mapper;
4
5
use TheIconic\NameParser\Part\AbstractPart;
6
use TheIconic\NameParser\Part\Salutation;
7
8
class SalutationMapper extends AbstractMapper
9
{
10
    protected $salutations = [];
11
12
    protected $maxIndex = 0;
13
14
    public function __construct(array $salutations, $maxIndex = 0)
15
    {
16
        $this->salutations = $salutations;
17
        $this->maxIndex = $maxIndex;
18
    }
19
20
    /**
21
     * map salutations in the 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
        $max = ($this->maxIndex > 0) ? $this->maxIndex : floor(count($parts) / 2);
29
30
        for ($k = 0; $k < $max; $k++) {
31
            if ($parts[$k] instanceof AbstractPart) {
32
                break;
33
            }
34
35
            $parts = $this->substituteWithSalutation($parts, $k);
36
        }
37
38
        return $parts;
39
    }
40
41
    protected function substituteWithSalutation(array $parts, int $start): array
42
    {
43
        foreach ($this->salutations as $key => $salutation) {
44
            $keys = explode(' ', $key);
45
            $length = count($keys);
46
47
            $subset = array_slice($parts, $start, $length);
48
49
            if ($this->isMatchingSubset($keys, $subset)) {
50
                array_splice($parts, $start, $length, [new Salutation(implode(' ', $subset), $salutation)]);
51
                return $parts;
52
            }
53
        }
54
55
        return $parts;
56
    }
57
58
    private function isMatchingSubset(array $keys, array $subset): bool
59
    {
60
        for ($i = 0; $i < count($subset); $i++) {
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...
61
            if ($this->getKey($subset[$i]) !== $keys[$i]) {
62
                return false;
63
            }
64
        }
65
66
        return true;
67
    }
68
}
69