Passed
Push — master ( b31236...fb684b )
by Alejandro
07:50 queued 04:27
created

Visitor   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 52
rs 10
ccs 19
cts 19
cp 1
wmc 8

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