Files
shlink/module/Core/src/Service/ShortUrlService.php

70 lines
1.9 KiB
PHP
Raw Normal View History

<?php
2016-07-19 18:01:39 +02:00
namespace Shlinkio\Shlink\Core\Service;
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Doctrine\ORM\EntityManagerInterface;
2016-07-19 17:38:41 +02:00
use Shlinkio\Shlink\Common\Paginator\Adapter\PaginableRepositoryAdapter;
2016-07-19 18:01:39 +02:00
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException;
2016-07-19 18:01:39 +02:00
use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
use Shlinkio\Shlink\Core\Util\TagManagerTrait;
use Zend\Paginator\Paginator;
class ShortUrlService implements ShortUrlServiceInterface
{
use TagManagerTrait;
/**
* @var EntityManagerInterface
*/
private $em;
/**
* ShortUrlService constructor.
* @param EntityManagerInterface $em
*
* @Inject({"em"})
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
2016-07-04 09:15:50 +02:00
* @param int $page
* @return Paginator|ShortUrl[]
*/
2016-07-04 09:15:50 +02:00
public function listShortUrls($page = 1)
{
2016-07-04 09:15:50 +02:00
/** @var ShortUrlRepository $repo */
$repo = $this->em->getRepository(ShortUrl::class);
$paginator = new Paginator(new PaginableRepositoryAdapter($repo));
$paginator->setItemCountPerPage(PaginableRepositoryAdapter::ITEMS_PER_PAGE)
->setCurrentPageNumber($page);
return $paginator;
}
/**
* @param string $shortCode
* @param string[] $tags
* @return ShortUrl
* @throws InvalidShortCodeException
*/
public function setTagsByShortCode($shortCode, array $tags = [])
{
/** @var ShortUrl $shortUrl */
$shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
'shortCode' => $shortCode,
]);
if (! isset($shortUrl)) {
throw InvalidShortCodeException::fromNotFoundShortCode($shortCode);
}
$shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));
$this->em->flush();
return $shortUrl;
}
}