Completed
Pull Request — master (#125)
by
unknown
02:05
created

BasicNetworkResolver::getRemoteIp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Yiisoft\Yii\Web\NetworkResolver;
5
6
use Psr\Http\Message\ServerRequestInterface;
7
8
class BasicNetworkResolver implements NetworkResolverInterface
9
{
10
    protected const SCHEME_HTTPS = 'https';
11
12
    /**
13
     * @var ServerRequestInterface|null
14
     */
15
    private $serverRequest;
16
17
    private $secureProtocolHeaders = [];
18
19
    public function getRemoteIp(): string
20
    {
21
        $ip = $this->getServerRequest()->getServerParams()['REMOTE_ADDR'] ?? null;
22
        if ($ip === null) {
23
            throw new \RuntimeException('Remote IP is not available!');
24
        }
25
        return (string)$ip;
26
    }
27
28
    public function getUserIp(): string
29
    {
30
        return $this->getRemoteIp();
31
    }
32
33 8
    public function getRequestScheme(): string
34
    {
35 8
        $request = $this->getServerRequest();
36 8
        foreach ($this->secureProtocolHeaders as $header => $values) {
37 6
            if (!$request->hasHeader($header) || !in_array(strtolower($request->getHeader($header)[0]), $values)) {
38 3
                continue;
39
            }
40 3
            return self::SCHEME_HTTPS;
41
        }
42 5
        return $request->getUri()->getScheme();
43
    }
44
45
    public function isSecureConnection(): bool
46
    {
47
        return $this->getRequestScheme() === self::SCHEME_HTTPS;
48
    }
49
50 8
    public function withServerRequest(ServerRequestInterface $serverRequest)
51
    {
52 8
        $new = clone $this;
53 8
        $new->serverRequest = $serverRequest;
54 8
        return $new;
55
    }
56
57
    /**
58
     * @TODO: currently https only, callback, http
59
     * @return static
60
     */
61 6
    public function withNewSecureProtocolHeader(string $header, array $valuesOfSecureProtocol)
62
    {
63 6
        $new = clone $this;
64 6
        if (count($valuesOfSecureProtocol) === 0) {
65
            throw new \RuntimeException('$valuesOfSecureProtocol cannot be an empty array!');
66
        }
67 6
        $new->secureProtocolHeaders[$header] = array_map('strtolower', $valuesOfSecureProtocol);
68 6
        return $new;
69
    }
70
71
72 8
    protected function getServerRequest(bool $throwIfNull = true): ?ServerRequestInterface
73
    {
74 8
        if ($this->serverRequest === null && $throwIfNull) {
75
            throw new \RuntimeException('The server request object is not set!');
76
        }
77 8
        return $this->serverRequest;
78
    }
79
}
80