Simplified transactional URL shortening

This commit is contained in:
Alejandro Celaya
2020-11-06 20:05:57 +01:00
parent 00255b04eb
commit 97f89bcede
11 changed files with 35 additions and 55 deletions

View File

@@ -16,6 +16,7 @@ use Shlinkio\Shlink\Core\Model\ShortUrlEdit;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Core\Validation\ShortUrlMetaInputFilter;
use Shlinkio\Shlink\Importer\Model\ImportedShlinkUrl;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use function count;
use function Shlinkio\Shlink\Core\generateRandomShortCode;
@@ -37,6 +38,7 @@ class ShortUrl extends AbstractEntity
private int $shortCodeLength;
private ?string $importSource = null;
private ?string $importOriginalShortCode = null;
private ?ApiKey $authorApiKey = null;
public function __construct(
string $longUrl,

View File

@@ -43,7 +43,7 @@ class UrlShortener implements UrlShortenerInterface
* @throws InvalidUrlException
* @throws Throwable
*/
public function urlToShortCode(string $url, array $tags, ShortUrlMeta $meta): ShortUrl
public function shorten(string $url, array $tags, ShortUrlMeta $meta): ShortUrl
{
// First, check if a short URL exists for all provided params
$existingShortUrl = $this->findExistingShortUrlIfExists($url, $tags, $meta);
@@ -52,25 +52,16 @@ class UrlShortener implements UrlShortenerInterface
}
$this->urlValidator->validateUrl($url, $meta->doValidateUrl());
$this->em->beginTransaction();
$shortUrl = new ShortUrl($url, $meta, $this->domainResolver);
$shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));
try {
return $this->em->transactional(function () use ($url, $tags, $meta) {
$shortUrl = new ShortUrl($url, $meta, $this->domainResolver);
$shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));
$this->verifyShortCodeUniqueness($meta, $shortUrl);
$this->em->persist($shortUrl);
$this->em->flush();
$this->em->commit();
} catch (Throwable $e) {
if ($this->em->getConnection()->isTransactionActive()) {
$this->em->rollback();
$this->em->close();
}
throw $e;
}
return $shortUrl;
return $shortUrl;
});
}
private function findExistingShortUrlIfExists(string $url, array $tags, ShortUrlMeta $meta): ?ShortUrl

View File

@@ -16,5 +16,5 @@ interface UrlShortenerInterface
* @throws NonUniqueSlugException
* @throws InvalidUrlException
*/
public function urlToShortCode(string $url, array $tags, ShortUrlMeta $meta): ShortUrl;
public function shorten(string $url, array $tags, ShortUrlMeta $meta): ShortUrl;
}