AllowedHostsFilter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 38
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A match() 0 10 2
A __construct() 0 13 3
1
<?php
2
namespace VDB\Spider\Filter\Prefetch;
3
4
use VDB\Spider\Filter\PreFetchFilterInterface;
5
use VDB\Uri\UriInterface;
6
7
/**
8
 * @author matthijs
9
 */
10
class AllowedHostsFilter implements PreFetchFilterInterface
11
{
12
    /** @var array The hostnames to filter links with */
13
    private $allowedHosts;
14
15
    private $allowSubDomains;
16
17
    /**
18
     * @param string[] $seeds
19
     * @param bool $allowSubDomains
20
     */
21
    public function __construct(array $seeds, $allowSubDomains = false)
22
    {
23
        $this->allowSubDomains = $allowSubDomains;
24
25
        foreach ($seeds as $seed) {
26
            $hostname = parse_url($seed, PHP_URL_HOST);
27
28
            if ($this->allowSubDomains) {
29
                // only use hostname.tld for comparison
30
                $this->allowedHosts[] = join('.', array_slice(explode('.', $hostname), -2));
31
            } else {
32
                // user entire *.hostname.tld for comparison
33
                $this->allowedHosts[] = $hostname;
34
            }
35
        }
36
    }
37
38
    public function match(UriInterface $uri)
39
    {
40
        $currentHostname = $uri->getHost();
41
42
        if ($this->allowSubDomains) {
43
            // only use hostname.tld for comparison
44
            $currentHostname = join('.', array_slice(explode('.', $currentHostname), -2));
45
        }
46
47
        return !in_array($currentHostname, $this->allowedHosts);
48
    }
49
}
50