ShortUrlService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Core\Service;
  4. use Doctrine\ORM;
  5. use Laminas\Paginator\Paginator;
  6. use Shlinkio\Shlink\Common\Util\DateRange;
  7. use Shlinkio\Shlink\Core\Entity\ShortUrl;
  8. use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
  9. use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
  10. use Shlinkio\Shlink\Core\Paginator\Adapter\ShortUrlRepositoryAdapter;
  11. use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
  12. use Shlinkio\Shlink\Core\Service\ShortUrl\FindShortCodeTrait;
  13. use Shlinkio\Shlink\Core\Util\TagManagerTrait;
  14. class ShortUrlService implements ShortUrlServiceInterface
  15. {
  16. use FindShortCodeTrait;
  17. use TagManagerTrait;
  18. private ORM\EntityManagerInterface $em;
  19. public function __construct(ORM\EntityManagerInterface $em)
  20. {
  21. $this->em = $em;
  22. }
  23. /**
  24. * @param string[] $tags
  25. * @param array|string|null $orderBy
  26. *
  27. * @return ShortUrl[]|Paginator
  28. */
  29. public function listShortUrls(
  30. int $page = 1,
  31. ?string $searchQuery = null,
  32. array $tags = [],
  33. $orderBy = null,
  34. ?DateRange $dateRange = null
  35. ) {
  36. /** @var ShortUrlRepository $repo */
  37. $repo = $this->em->getRepository(ShortUrl::class);
  38. $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $searchQuery, $tags, $orderBy, $dateRange));
  39. $paginator->setItemCountPerPage(ShortUrlRepositoryAdapter::ITEMS_PER_PAGE)
  40. ->setCurrentPageNumber($page);
  41. return $paginator;
  42. }
  43. /**
  44. * @param string[] $tags
  45. * @throws ShortUrlNotFoundException
  46. */
  47. public function setTagsByShortCode(string $shortCode, array $tags = []): ShortUrl
  48. {
  49. $shortUrl = $this->findByShortCode($this->em, $shortCode);
  50. $shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));
  51. $this->em->flush();
  52. return $shortUrl;
  53. }
  54. /**
  55. * @throws ShortUrlNotFoundException
  56. */
  57. public function updateMetadataByShortCode(string $shortCode, ShortUrlMeta $shortUrlMeta): ShortUrl
  58. {
  59. $shortUrl = $this->findByShortCode($this->em, $shortCode);
  60. $shortUrl->updateMeta($shortUrlMeta);
  61. $this->em->flush();
  62. return $shortUrl;
  63. }
  64. }