Visitor   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 18
dl 0
loc 49
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getReferer() 0 3 1
A getUserAgent() 0 3 1
A emptyInstance() 0 3 1
A __construct() 0 5 1
A cropToLength() 0 3 2
A getRemoteAddress() 0 3 1
A fromRequest() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Model;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
use Shlinkio\Shlink\Common\Middleware\IpAddressMiddlewareFactory;
9
10
use function substr;
11
12
final class Visitor
13
{
14
    public const USER_AGENT_MAX_LENGTH = 512;
15
    public const REFERER_MAX_LENGTH = 1024;
16
    public const REMOTE_ADDRESS_MAX_LENGTH = 256;
17
18
    private string $userAgent;
19
    private string $referer;
20
    private ?string $remoteAddress;
21
22 57
    public function __construct(string $userAgent, string $referer, ?string $remoteAddress)
23
    {
24 57
        $this->userAgent = $this->cropToLength($userAgent, self::USER_AGENT_MAX_LENGTH);
25 57
        $this->referer = $this->cropToLength($referer, self::REFERER_MAX_LENGTH);
26 57
        $this->remoteAddress = $this->cropToLength($remoteAddress, self::REMOTE_ADDRESS_MAX_LENGTH);
27 57
    }
28
29 57
    private function cropToLength(?string $value, int $length): ?string
30
    {
31 57
        return $value === null ? null : substr($value, 0, $length);
32
    }
33
34 12
    public static function fromRequest(ServerRequestInterface $request): self
35
    {
36 12
        return new self(
37 12
            $request->getHeaderLine('User-Agent'),
38 12
            $request->getHeaderLine('Referer'),
39 12
            $request->getAttribute(IpAddressMiddlewareFactory::REQUEST_ATTR),
40
        );
41
    }
42
43 21
    public static function emptyInstance(): self
44
    {
45 21
        return new self('', '', null);
46
    }
47
48 46
    public function getUserAgent(): string
49
    {
50 46
        return $this->userAgent;
51
    }
52
53 46
    public function getReferer(): string
54
    {
55 46
        return $this->referer;
56
    }
57
58 46
    public function getRemoteAddress(): ?string
59
    {
60 46
        return $this->remoteAddress;
61
    }
62
}
63