Completed
Pull Request — develop (#680)
by Alejandro
05:10
created

VisitorTest::generateRandomString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ShlinkioTest\Shlink\Core\Model;
6
7
use PHPUnit\Framework\TestCase;
8
use Shlinkio\Shlink\Core\Model\Visitor;
9
10
use function random_int;
11
use function str_repeat;
12
use function strlen;
13
use function substr;
14
15
class VisitorTest extends TestCase
16
{
17
    /**
18
     * @test
19
     * @dataProvider provideParams
20
     */
21
    public function providedFieldsValuesAreCropped(array $params, array $expected): void
22
    {
23
        $visitor = new Visitor(...$params);
24
        ['userAgent' => $userAgent, 'referer' => $referer, 'remoteAddress' => $remoteAddress] = $expected;
25
26
        $this->assertEquals($userAgent, $visitor->getUserAgent());
27
        $this->assertEquals($referer, $visitor->getReferer());
28
        $this->assertEquals($remoteAddress, $visitor->getRemoteAddress());
29
    }
30
31
    public function provideParams(): iterable
32
    {
33
        yield 'all values are bigger' => [
34
            [str_repeat('a', 1000), str_repeat('b', 2000), str_repeat('c', 500)],
35
            [
36
                'userAgent' => str_repeat('a', Visitor::USER_AGENT_MAX_LENGTH),
37
                'referer' => str_repeat('b', Visitor::REFERER_MAX_LENGTH),
38
                'remoteAddress' => str_repeat('c', Visitor::REMOTE_ADDRESS_MAX_LENGTH),
39
            ],
40
        ];
41
        yield 'some values are smaller' => [
42
            [str_repeat('a', 10), str_repeat('b', 2000), null],
43
            [
44
                'userAgent' => str_repeat('a', 10),
45
                'referer' => str_repeat('b', Visitor::REFERER_MAX_LENGTH),
46
                'remoteAddress' => null,
47
            ],
48
        ];
49
        yield 'random strings' => [
50
            [
51
                $userAgent = $this->generateRandomString(2000),
52
                $referer = $this->generateRandomString(50),
53
                null,
54
            ],
55
            [
56
                'userAgent' => substr($userAgent, 0, Visitor::USER_AGENT_MAX_LENGTH),
57
                'referer' => $referer,
58
                'remoteAddress' => null,
59
            ],
60
        ];
61
    }
62
63
    private function generateRandomString(int $length): string
64
    {
65
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
66
        $charactersLength = strlen($characters);
67
        $randomString = '';
68
        for ($i = 0; $i < $length; $i++) {
69
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
70
        }
71
        return $randomString;
72
    }
73
}
74