ShortUrlService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Core\Service;
  4. use Doctrine\ORM;
  5. use Shlinkio\Shlink\Common\Paginator\Paginator;
  6. use Shlinkio\Shlink\Core\Entity\ShortUrl;
  7. use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
  8. use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
  9. use Shlinkio\Shlink\Core\Model\ShortUrlEdit;
  10. use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
  11. use Shlinkio\Shlink\Core\Model\ShortUrlsParams;
  12. use Shlinkio\Shlink\Core\Paginator\Adapter\ShortUrlRepositoryAdapter;
  13. use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
  14. use Shlinkio\Shlink\Core\Service\ShortUrl\ShortUrlResolverInterface;
  15. use Shlinkio\Shlink\Core\ShortUrl\Resolver\ShortUrlRelationResolverInterface;
  16. use Shlinkio\Shlink\Core\Util\UrlValidatorInterface;
  17. use Shlinkio\Shlink\Rest\Entity\ApiKey;
  18. class ShortUrlService implements ShortUrlServiceInterface
  19. {
  20. private ORM\EntityManagerInterface $em;
  21. private ShortUrlResolverInterface $urlResolver;
  22. private UrlValidatorInterface $urlValidator;
  23. private ShortUrlRelationResolverInterface $relationResolver;
  24. public function __construct(
  25. ORM\EntityManagerInterface $em,
  26. ShortUrlResolverInterface $urlResolver,
  27. UrlValidatorInterface $urlValidator,
  28. ShortUrlRelationResolverInterface $relationResolver
  29. ) {
  30. $this->em = $em;
  31. $this->urlResolver = $urlResolver;
  32. $this->urlValidator = $urlValidator;
  33. $this->relationResolver = $relationResolver;
  34. }
  35. /**
  36. * @return ShortUrl[]|Paginator
  37. */
  38. public function listShortUrls(ShortUrlsParams $params, ?ApiKey $apiKey = null): Paginator
  39. {
  40. /** @var ShortUrlRepository $repo */
  41. $repo = $this->em->getRepository(ShortUrl::class);
  42. $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $params, $apiKey));
  43. $paginator->setMaxPerPage($params->itemsPerPage())
  44. ->setCurrentPage($params->page());
  45. return $paginator;
  46. }
  47. /**
  48. * @throws ShortUrlNotFoundException
  49. * @throws InvalidUrlException
  50. */
  51. public function updateShortUrl(
  52. ShortUrlIdentifier $identifier,
  53. ShortUrlEdit $shortUrlEdit,
  54. ?ApiKey $apiKey = null
  55. ): ShortUrl {
  56. if ($shortUrlEdit->hasLongUrl()) {
  57. $this->urlValidator->validateUrl($shortUrlEdit->longUrl(), $shortUrlEdit->doValidateUrl());
  58. }
  59. $shortUrl = $this->urlResolver->resolveShortUrl($identifier, $apiKey);
  60. $shortUrl->update($shortUrlEdit, $this->relationResolver);
  61. $this->em->flush();
  62. return $shortUrl;
  63. }
  64. }