Completed
Push — master ( e8b19e...87df92 )
by Andrew
02:42
created

Engine::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace KRDigital\NamesDetector\Engine;
6
7
use KRDigital\NamesDetector\Config\ConfigInterface;
8
use KRDigital\NamesDetector\Entry\Entry;
9
use KRDigital\NamesDetector\Entry\Type;
10
use KRDigital\NamesDetector\Exception\InvalidSearchInputException;
11
12
class Engine implements EngineInterface
13
{
14
    /**
15
     * @var ConfigInterface
16
     */
17
    protected $config;
18
19 9
    public function __construct(ConfigInterface $config)
20
    {
21 9
        $this->config = $config;
22 9
    }
23
24 5
    public function extractFirstName(string $input, bool $strict = false): ?Entry
25
    {
26 5
        return $this->findValueByType($input, Type::TYPE_FIRST_NAME, $strict);
27
    }
28
29 4
    public function extractMiddleName(string $input, bool $strict = false): ?Entry
30
    {
31 4
        return $this->findValueByType($input, Type::TYPE_MIDDLE_NAME, $strict);
32
    }
33
34 9
    protected function findValueByType(string $input, string $type, bool $strict): ?Entry
35
    {
36 9
        $entry = null;
37 9
        $resultsQuantity = 0;
38 9
        foreach (\explode(' ', $input) as $value) {
39
            switch ($type) {
40 9
                case Type::TYPE_FIRST_NAME:
41 5
                    $result = $this->config->getDictionary()->findFirstName($value);
42 5
                    break;
43 4
                case Type::TYPE_MIDDLE_NAME:
44 4
                    $result = $this->config->getDictionary()->findMiddleName($value);
45 4
                    break;
46
                default:
47
                    throw new \LogicException(\sprintf('Invalid type %s', $type));
48
            }
49
50 9
            if (null !== $result) {
51 9
                if (!$strict) {
52 8
                    return $result;
53
                }
54
55 1
                $entry = $result;
56
57 1
                ++$resultsQuantity;
58
            }
59
        }
60
61 1
        if ($strict && $resultsQuantity > 1) {
62 1
            throw new InvalidSearchInputException(\sprintf('%d values detected in input %s', $resultsQuantity, $input));
63
        }
64
65
        return $entry;
66
    }
67
}
68