mirror of
https://github.com/shlinkio/shlink.git
synced 2026-03-09 16:53:11 +08:00
Simplified transactional URL shortening
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user