Completed
Push — master ( 7bb037...8474c3 )
by Andrew
02:55
created

Dictionary   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
eloc 22
dl 0
loc 59
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A fromArray() 0 7 2
A findMiddleName() 0 11 2
A getKey() 0 9 2
A findFirstName() 0 11 2
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
11
class Dictionary implements DictionaryInterface
12
{
13
    protected $firstNames;
14
15
    protected $middleNames;
16
17 10
    protected function __construct(array $firstNames, array $middleNames)
18
    {
19 10
        $this->firstNames = $firstNames;
20 10
        $this->middleNames = $middleNames;
21 10
    }
22
23 11
    public static function fromArray(array $data): self
24
    {
25 11
        if ($diff = \array_diff(['first_names', 'middle_names'], \array_keys($data))) {
26 1
            throw new InvalidDictionaryInputDataException('Input dictionary keys missing', $diff);
27
        }
28
29 10
        return new static($data['first_names'], $data['middle_names']);
30
    }
31
32 5
    public function findFirstName(string $name): ?Entry
33
    {
34 5
        $key = self::getKey($name, $this->firstNames);
35
36 5
        $result = $this->firstNames[$key] ?? null;
37
38 5
        if (null !== $result) {
39 4
            return Entry::fromArray(['type' => Type::TYPE_FIRST_NAME, 'gender' => $result[1] ?? null, 'value' => $result[0] ?? null]);
40
        }
41
42 1
        return null;
43
    }
44
45 5
    public function findMiddleName(string $name): ?Entry
46
    {
47 5
        $key = self::getKey($name, $this->middleNames);
48
49 5
        $result = $this->middleNames[$key] ?? null;
50
51 5
        if (null !== $result) {
52 4
            return Entry::fromArray(['type' => Type::TYPE_MIDDLE_NAME, 'gender' => $result[1] ?? null, 'value' => $result[0] ?? null]);
53
        }
54
55 1
        return null;
56
    }
57
58
    /**
59
     * @return int|string|null
60
     */
61 10
    protected static function getKey(string $name, array $data)
62
    {
63 10
        $key = \array_search(\ucfirst(\strtolower($name)), \array_column($data, 0), true);
64
65 10
        if (false === $key) {
66 2
            return null;
67
        }
68
69 8
        return $key;
70
    }
71
}
72