Dictionary::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace KRDigital\NamesDetector\Dictionary;
6
7
use KRDigital\NamesDetector\Entry\Entry;
8
use KRDigital\NamesDetector\Entry\Type;
9
use KRDigital\NamesDetector\Exception\InvalidDictionaryInputDataException;
10
use KRDigital\NamesDetector\Util\StringUtil;
11
12
class Dictionary implements DictionaryInterface
13
{
14
    protected $firstNames;
15
16
    protected $middleNames;
17
18 10
    protected function __construct(array $firstNames, array $middleNames)
19
    {
20 10
        $this->firstNames = $firstNames;
21 10
        $this->middleNames = $middleNames;
22 10
    }
23
24 11
    public static function fromArray(array $data): self
25
    {
26 11
        if ($diff = \array_diff(['first_names', 'middle_names'], \array_keys($data))) {
27 1
            throw new InvalidDictionaryInputDataException('Input dictionary keys missing', $diff);
28
        }
29
30 10
        return new static($data['first_names'], $data['middle_names']);
31
    }
32
33 5
    public function findFirstName(string $name): ?Entry
34
    {
35 5
        $key = self::getKey($name, $this->firstNames);
36
37 5
        $result = $this->firstNames[$key] ?? null;
38
39 5
        if (null !== $result) {
40 4
            return Entry::fromArray(['type' => Type::TYPE_FIRST_NAME, 'gender' => $result[1] ?? null, 'value' => $result[0] ?? null]);
41
        }
42
43 1
        return null;
44
    }
45
46 5
    public function findMiddleName(string $name): ?Entry
47
    {
48 5
        $key = self::getKey($name, $this->middleNames);
49
50 5
        $result = $this->middleNames[$key] ?? null;
51
52 5
        if (null !== $result) {
53 4
            return Entry::fromArray(['type' => Type::TYPE_MIDDLE_NAME, 'gender' => $result[1] ?? null, 'value' => $result[0] ?? null]);
54
        }
55
56 1
        return null;
57
    }
58
59
    /**
60
     * @return int|string|null
61
     */
62 10
    protected static function getKey(string $name, array $data)
63
    {
64 10
        $key = \array_search(StringUtil::capitalize($name), \array_column($data, 0), true);
65
66 10
        if (false === $key) {
67 2
            return null;
68
        }
69
70 8
        return $key;
71
    }
72
}
73