1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace ShlinkioTest\Shlink\Core\Entity; |
6
|
|
|
|
7
|
|
|
use PHPUnit\Framework\TestCase; |
8
|
|
|
use Shlinkio\Shlink\Core\Entity\ShortUrl; |
9
|
|
|
use Shlinkio\Shlink\Core\Exception\ShortCodeCannotBeRegeneratedException; |
10
|
|
|
use Shlinkio\Shlink\Core\Model\ShortUrlMeta; |
11
|
|
|
use Shlinkio\Shlink\Core\Validation\ShortUrlMetaInputFilter; |
12
|
|
|
|
13
|
|
|
use function Functional\map; |
14
|
|
|
use function range; |
15
|
|
|
use function strlen; |
16
|
|
|
|
17
|
|
|
use const Shlinkio\Shlink\Core\DEFAULT_SHORT_CODES_LENGTH; |
|
|
|
|
18
|
|
|
|
19
|
|
|
class ShortUrlTest extends TestCase |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @test |
23
|
|
|
* @dataProvider provideInvalidShortUrls |
24
|
|
|
*/ |
25
|
|
|
public function regenerateShortCodeThrowsExceptionIfStateIsInvalid( |
26
|
|
|
ShortUrl $shortUrl, |
27
|
|
|
string $expectedMessage |
28
|
|
|
): void { |
29
|
|
|
$this->expectException(ShortCodeCannotBeRegeneratedException::class); |
30
|
|
|
$this->expectExceptionMessage($expectedMessage); |
31
|
|
|
|
32
|
|
|
$shortUrl->regenerateShortCode(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function provideInvalidShortUrls(): iterable |
36
|
|
|
{ |
37
|
|
|
yield 'with custom slug' => [ |
38
|
|
|
new ShortUrl('', ShortUrlMeta::fromRawData(['customSlug' => 'custom-slug'])), |
39
|
|
|
'The short code cannot be regenerated on ShortUrls where a custom slug was provided.', |
40
|
|
|
]; |
41
|
|
|
yield 'already persisted' => [ |
42
|
|
|
(new ShortUrl(''))->setId('1'), |
43
|
|
|
'The short code can be regenerated only on new ShortUrls which have not been persisted yet.', |
44
|
|
|
]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** @test */ |
48
|
|
|
public function regenerateShortCodeProperlyChangesTheValueOnValidShortUrls(): void |
49
|
|
|
{ |
50
|
|
|
$shortUrl = new ShortUrl(''); |
51
|
|
|
$firstShortCode = $shortUrl->getShortCode(); |
52
|
|
|
|
53
|
|
|
$shortUrl->regenerateShortCode(); |
54
|
|
|
$secondShortCode = $shortUrl->getShortCode(); |
55
|
|
|
|
56
|
|
|
$this->assertNotEquals($firstShortCode, $secondShortCode); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @test |
61
|
|
|
* @dataProvider provideLengths |
62
|
|
|
*/ |
63
|
|
|
public function shortCodesHaveExpectedLength(?int $length, int $expectedLength): void |
64
|
|
|
{ |
65
|
|
|
$shortUrl = new ShortUrl('', ShortUrlMeta::fromRawData( |
66
|
|
|
[ShortUrlMetaInputFilter::SHORT_CODE_LENGTH => $length], |
67
|
|
|
)); |
68
|
|
|
|
69
|
|
|
$this->assertEquals($expectedLength, strlen($shortUrl->getShortCode())); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function provideLengths(): iterable |
73
|
|
|
{ |
74
|
|
|
yield [null, DEFAULT_SHORT_CODES_LENGTH]; |
75
|
|
|
yield from map(range(4, 10), fn (int $value) => [$value, $value]); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|