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

NamesDetector::extractMiddleName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 5
c 1
b 0
f 1
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace KRDigital\NamesDetector;
6
7
use KRDigital\NamesDetector\Config\ConfigInterface;
8
use KRDigital\NamesDetector\Engine\EngineFactory;
9
use KRDigital\NamesDetector\Engine\EngineInterface;
10
use KRDigital\NamesDetector\Entry\Entry;
11
use KRDigital\NamesDetector\Entry\Prefix\Prefix;
12
use KRDigital\NamesDetector\Entry\Prefix\PrefixInterface;
13
use KRDigital\NamesDetector\Exception\InvalidSearchInputException;
14
15
class NamesDetector
16
{
17
    /**
18
     * @var EngineInterface
19
     */
20
    protected $engine;
21
22 129
    public function __construct(ConfigInterface $config = null, EngineInterface $engine = null)
23
    {
24 129
        $this->engine = $engine ?? EngineFactory::create($config);
25 129
    }
26
27
    /**
28
     * @param bool $strictSearch return null when extract multiple names
29
     */
30 128
    public function extractFirstName(string $input, bool $strictSearch = false): ?Entry
31
    {
32
        try {
33 128
            $result = $this->engine->extractFirstName($input, $strictSearch);
34 1
        } catch (InvalidSearchInputException $exception) {
35 1
            return null;
36
        }
37
38 127
        return $result;
39
    }
40
41
    /**
42
     * @param bool $strictSearch return null when extract multiple names
43
     */
44 126
    public function extractMiddleName(string $input, bool $strictSearch = false): ?Entry
45
    {
46
        try {
47 126
            $result = $this->engine->extractMiddleName($input, $strictSearch);
48 1
        } catch (InvalidSearchInputException $exception) {
49 1
            return null;
50
        }
51
52 125
        return $result;
53
    }
54
55 127
    public function createTitle(string $input, PrefixInterface $prefix = null): ?string
56
    {
57 127
        if (null === $prefix) {
58 65
            $prefix = new Prefix();
59
        }
60
61 127
        $firstName = $this->extractFirstName($input, true);
62
63 127
        if (null === $firstName) {
64 2
            return null;
65
        }
66
67 125
        $middleName = $this->extractMiddleName($input, true);
68
69 125
        if (null === $middleName || !$firstName->getGender()->equals($middleName->getGender())) {
70 1
            return null;
71
        }
72
73 124
        return \sprintf('%s %s %s', $prefix->getPrefixByGender($firstName->getGender()), $firstName->getValue(), $middleName->getValue());
74
    }
75
}
76