Visitor::getUserAgent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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