|
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
|
|
|
|