Passed
Pull Request — master (#125)
by
unknown
03:16
created

BasicNetworkResolver   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 50
ccs 0
cts 37
cp 0
rs 10
c 1
b 0
f 0
wmc 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getServerRequest() 0 6 3
A withServerRequest() 0 5 1
A getRemoteIp() 0 7 2
A getRequestScheme() 0 3 1
A getUserIp() 0 3 1
A setServerRequest() 0 4 1
A isSecureConnection() 0 3 1
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
    /**
11
     * @var ServerRequestInterface|null
12
     */
13
    private $serverRequest;
14
15
    public function getRemoteIp(): string
16
    {
17
        $ip = $this->getServerRequest()->getServerParams()['REMOTE_ADDR'] ?? null;
18
        if ($ip === null) {
19
            throw new \RuntimeException('Remote IP is not available!');
20
        }
21
        return (string)$ip;
22
    }
23
24
    public function getUserIp(): string
25
    {
26
        return $this->getRemoteIp();
27
    }
28
29
    public function getRequestScheme(): string
30
    {
31
        return $this->getServerRequest()->getUri()->getScheme();
32
    }
33
34
    public function isSecureConnection(): bool
35
    {
36
        return $this->getRequestScheme() === 'https';
37
    }
38
39
    public function setServerRequest(ServerRequestInterface $serverRequest)
40
    {
41
        $this->serverRequest = $serverRequest;
42
        return $this;
43
    }
44
45
    public function withServerRequest(ServerRequestInterface $serverRequest)
46
    {
47
        $new = clone $this;
48
        $new->setServerRequest($serverRequest);
49
        return $new;
50
    }
51
52
    protected function getServerRequest(bool $throwIfNull = true): ?ServerRequestInterface
53
    {
54
        if ($this->serverRequest === null && $throwIfNull) {
55
            throw new \RuntimeException('The server request object is not set!');
56
        }
57
        return $this->serverRequest;
58
    }
59
}
60