SuffixVisitor   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 46
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A visit() 0 13 4
A findSuffix() 0 9 3
1
<?php
2
3
namespace BenTools\HostnameExtractor\Visitor;
4
5
use BenTools\HostnameExtractor\ParsedHostname;
6
use BenTools\HostnameExtractor\SuffixProvider\NaiveSuffixProvider;
7
use BenTools\HostnameExtractor\SuffixProvider\SuffixProviderInterface;
8
use BenTools\Violin\Violin;
9
use function BenTools\Violin\string;
10
11
/**
12
 * Class SuffixVisitor
13
 * @internal
14
 */
15
final class SuffixVisitor implements HostnameVisitorInterface
16
{
17
    /**
18
     * @var SuffixProviderInterface
19
     */
20
    private $suffixProvider;
21
22
    /**
23
     * @inheritDoc
24
     */
25
    public function __construct(SuffixProviderInterface $suffixProvider = null)
26
    {
27
        $this->suffixProvider = $suffixProvider ?? new NaiveSuffixProvider();
28
    }
29
30
    /**
31
     * @inheritDoc
32
     */
33
    public function visit($hostname, ParsedHostname $parsedHostname): void
34
    {
35
        $hostname = string($hostname);
36
        if (!$parsedHostname->isIp() && $hostname->contains('.')) {
37
            $suffix = $this->findSuffix($hostname);
38
            if (null !== $suffix) {
39
                $parsedHostname->setSuffix($suffix);
40
            } else {
41
                $hostnameParts = \explode('.', $hostname);
42
                $parsedHostname->setSuffix(\array_pop($hostnameParts));
43
            }
44
        }
45
    }
46
47
    /**
48
     * @param Violin $hostname
49
     * @return null|string
50
     */
51
    private function findSuffix(Violin $hostname): ?string
52
    {
53
        foreach ($this->suffixProvider->getSuffixes() as $suffix) {
54
            if ($hostname->endsWith(\sprintf('.%s', $suffix))) {
55
                return $suffix;
56
            }
57
        }
58
        return null;
59
    }
60
}
61