shlink/module/Core/test/Entity/ShortUrlTest.php

92 lines
2.8 KiB
PHP
Raw Normal View History

2019-10-11 04:28:53 -05:00
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\Entity;
use Cake\Chronos\Chronos;
2019-10-11 04:28:53 -05:00
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortCodeCannotBeRegeneratedException;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Core\Validation\ShortUrlInputFilter;
use Shlinkio\Shlink\Importer\Model\ImportedShlinkUrl;
2022-08-07 02:36:51 -05:00
use Shlinkio\Shlink\Importer\Sources\ImportSource;
use function Functional\map;
use function range;
use function strlen;
use const Shlinkio\Shlink\DEFAULT_SHORT_CODES_LENGTH;
2019-10-11 04:28:53 -05:00
class ShortUrlTest extends TestCase
{
/**
* @test
* @dataProvider provideInvalidShortUrls
*/
public function regenerateShortCodeThrowsExceptionIfStateIsInvalid(
ShortUrl $shortUrl,
string $expectedMessage,
2019-10-11 04:28:53 -05:00
): void {
$this->expectException(ShortCodeCannotBeRegeneratedException::class);
$this->expectExceptionMessage($expectedMessage);
$shortUrl->regenerateShortCode();
}
public function provideInvalidShortUrls(): iterable
{
yield 'with custom slug' => [
ShortUrl::fromMeta(ShortUrlMeta::fromRawData(['customSlug' => 'custom-slug', 'longUrl' => ''])),
2019-10-11 04:28:53 -05:00
'The short code cannot be regenerated on ShortUrls where a custom slug was provided.',
];
yield 'already persisted' => [
ShortUrl::createEmpty()->setId('1'),
2019-10-11 04:28:53 -05:00
'The short code can be regenerated only on new ShortUrls which have not been persisted yet.',
];
}
/**
* @test
* @dataProvider provideValidShortUrls
*/
public function regenerateShortCodeProperlyChangesTheValueOnValidShortUrls(ShortUrl $shortUrl): void
2019-10-11 04:28:53 -05:00
{
$firstShortCode = $shortUrl->getShortCode();
$shortUrl->regenerateShortCode();
$secondShortCode = $shortUrl->getShortCode();
2020-10-03 17:35:14 -05:00
self::assertNotEquals($firstShortCode, $secondShortCode);
2019-10-11 04:28:53 -05:00
}
public function provideValidShortUrls(): iterable
{
yield 'no custom slug' => [ShortUrl::createEmpty()];
2022-08-07 02:36:51 -05:00
yield 'imported with custom slug' => [ShortUrl::fromImport(
new ImportedShlinkUrl(ImportSource::BITLY, '', [], Chronos::now(), null, 'custom-slug', null),
true,
)];
}
/**
* @test
* @dataProvider provideLengths
*/
public function shortCodesHaveExpectedLength(?int $length, int $expectedLength): void
{
$shortUrl = ShortUrl::fromMeta(ShortUrlMeta::fromRawData(
[ShortUrlInputFilter::SHORT_CODE_LENGTH => $length, 'longUrl' => ''],
));
2020-10-03 17:35:14 -05:00
self::assertEquals($expectedLength, strlen($shortUrl->getShortCode()));
}
public function provideLengths(): iterable
{
yield [null, DEFAULT_SHORT_CODES_LENGTH];
yield from map(range(4, 10), fn (int $value) => [$value, $value]);
}
2019-10-11 04:28:53 -05:00
}