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

BasicNetworkResolver::getRequestScheme()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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