Used maxVisits field when creating or fetching a ShortUrl

This commit is contained in:
Alejandro Celaya
2017-10-22 09:15:37 +02:00
parent af7c11665c
commit cb23d38b38
6 changed files with 21 additions and 8 deletions

View File

@@ -224,7 +224,7 @@ class ShortUrl extends AbstractEntity implements \JsonSerializable
public function maxVisitsReached(): bool
{
return $this->maxVisits !== null && $this->maxVisits >= $this->getVisitsCount();
return $this->maxVisits !== null && $this->getVisitsCount() >= $this->maxVisits;
}
/**

View File

@@ -145,6 +145,8 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
->setParameter('now', $now)
->setMaxResults(1);
return $qb->getQuery()->getOneOrNullResult();
/** @var ShortUrl|null $result */
$result = $qb->getQuery()->getOneOrNullResult();
return $result === null || $result->maxVisitsReached() ? null : $result;
}
}

View File

@@ -69,6 +69,7 @@ class UrlShortener implements UrlShortenerInterface
* @param \DateTime|null $validSince
* @param \DateTime|null $validUntil
* @param string|null $customSlug
* @param int|null $maxVisits
* @return string
* @throws NonUniqueSlugException
* @throws InvalidUrlException
@@ -79,7 +80,8 @@ class UrlShortener implements UrlShortenerInterface
array $tags = [],
\DateTime $validSince = null,
\DateTime $validUntil = null,
string $customSlug = null
string $customSlug = null,
int $maxVisits = null
): string {
// If the url already exists in the database, just return its short code
$shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
@@ -101,7 +103,8 @@ class UrlShortener implements UrlShortenerInterface
$shortUrl = new ShortUrl();
$shortUrl->setOriginalUrl((string) $url)
->setValidSince($validSince)
->setValidUntil($validUntil);
->setValidUntil($validUntil)
->setMaxVisits($maxVisits);
$this->em->persist($shortUrl);
$this->em->flush();
@@ -146,7 +149,7 @@ class UrlShortener implements UrlShortenerInterface
* @param int $id
* @return string
*/
private function convertAutoincrementIdToShortCode($id)
private function convertAutoincrementIdToShortCode($id): string
{
$id = ((int) $id) + 200000; // Increment the Id so that the generated shortcode is not too short
$length = strlen($this->chars);

View File

@@ -20,6 +20,7 @@ interface UrlShortenerInterface
* @param \DateTime|null $validSince
* @param \DateTime|null $validUntil
* @param string|null $customSlug
* @param int|null $maxVisits
* @return string
* @throws NonUniqueSlugException
* @throws InvalidUrlException
@@ -30,7 +31,8 @@ interface UrlShortenerInterface
array $tags = [],
\DateTime $validSince = null,
\DateTime $validUntil = null,
string $customSlug = null
string $customSlug = null,
int $maxVisits = null
): string;
/**