Passed
Push — master ( 8a9e6c...ec351d )
by
03:16
created

BlockedServersCollection::offsetExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Ely\Mojang\Response;
5
6
use ArrayAccess;
7
use Countable;
8
use InvalidArgumentException;
9
10
class BlockedServersCollection implements ArrayAccess, Countable {
11
12
    /**
13
     * @var string[]
14
     */
15
    private $hashes;
16
17 15
    public function __construct(array $hashes) {
18 15
        $this->hashes = $hashes;
19 15
    }
20
21 1
    public function offsetExists($offset): bool {
22 1
        return isset($this->hashes[$offset]);
23
    }
24
25 1
    public function offsetGet($offset): string {
26 1
        return $this->hashes[$offset];
27
    }
28
29 1
    public function offsetSet($offset, $value): void {
30 1
        $this->hashes[$offset] = $value;
31 1
    }
32
33 1
    public function offsetUnset($offset): void {
34 1
        unset($this->hashes[$offset]);
35 1
    }
36
37 2
    public function count(): int {
38 2
        return count($this->hashes);
39
    }
40
41
    /**
42
     * @param string $serverName
43
     *
44
     * @return bool
45
     *
46
     * @link https://wiki.vg/Mojang_API#Blocked_Servers
47
     */
48 12
    public function isBlocked(string $serverName): bool {
49 12
        if (filter_var($serverName, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
50 1
            throw new InvalidArgumentException('Minecraft does not support IPv6, so this library too');
51
        }
52
53 11
        $isIp = filter_var($serverName, FILTER_VALIDATE_IP) !== false;
54 11
        foreach ($this->generateSubstitutions(mb_strtolower($serverName), $isIp) as $mask) {
55 11
            $hash = sha1($mask);
56 11
            if (in_array($hash, $this->hashes, true)) {
57 11
                return true;
58
            }
59
        }
60
61 5
        return false;
62
    }
63
64 11
    private function generateSubstitutions(string $input, bool $right): iterable {
65 11
        yield $input;
66 9
        $parts = explode('.', $input);
67 9
        while (count($parts) > 1) {
68 9
            if ($right) {
69 3
                array_pop($parts);
70 3
                yield implode('.', $parts) . '.*';
71
            } else {
72 6
                array_shift($parts);
73 6
                yield '*.' . implode('.', $parts);
74
            }
75
        }
76 5
    }
77
78
}
79