Updated logic to generate random short codes, increasing entropy

This commit is contained in:
Alejandro Celaya
2019-10-11 09:14:25 +02:00
parent c8d950e04d
commit 2f09ff456c
13 changed files with 91 additions and 149 deletions

View File

@@ -7,6 +7,7 @@ namespace Shlinkio\Shlink\Core\Entity;
use Cake\Chronos\Chronos;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use PUGX\Shortid\Factory as ShortIdFactory;
use Shlinkio\Shlink\Common\Entity\AbstractEntity;
use Shlinkio\Shlink\Core\Domain\Resolver\DomainResolverInterface;
use Shlinkio\Shlink\Core\Domain\Resolver\SimpleDomainResolver;
@@ -20,6 +21,8 @@ use function Functional\invoke;
class ShortUrl extends AbstractEntity
{
private const BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/** @var string */
private $longUrl;
/** @var string */
@@ -53,10 +56,15 @@ class ShortUrl extends AbstractEntity
$this->validSince = $meta->getValidSince();
$this->validUntil = $meta->getValidUntil();
$this->maxVisits = $meta->getMaxVisits();
$this->shortCode = $meta->getCustomSlug() ?? ''; // TODO logic to calculate short code should be passed somehow
$this->shortCode = $meta->getCustomSlug() ?? $this->generateShortCode();
$this->domain = ($domainResolver ?? new SimpleDomainResolver())->resolveDomain($meta->getDomain());
}
private function generateShortCode(): string
{
return (new ShortIdFactory())->generate(6, self::BASE62)->serialize();
}
public function getLongUrl(): string
{
return $this->longUrl;
@@ -67,13 +75,6 @@ class ShortUrl extends AbstractEntity
return $this->shortCode;
}
// TODO Short code is currently calculated based on the ID, so a setter is needed
public function setShortCode(string $shortCode): self
{
$this->shortCode = $shortCode;
return $this;
}
public function getDateCreated(): Chronos
{
return $this->dateCreated;