コード例 #1
0
ファイル: UrlShortener.php プロジェクト: shlinkio/shlink
 /**
  * Creates and persists a unique shortcode generated for provided url
  *
  * @param UriInterface $url
  * @param string[] $tags
  * @return string
  * @throws InvalidUrlException
  * @throws RuntimeException
  */
 public function urlToShortCode(UriInterface $url, array $tags = [])
 {
     // If the url already exists in the database, just return its short code
     $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy(['originalUrl' => $url]);
     if (isset($shortUrl)) {
         return $shortUrl->getShortCode();
     }
     // Check that the URL exists
     $this->checkUrlExists($url);
     // Transactionally insert the short url, then generate the short code and finally update the short code
     try {
         $this->em->beginTransaction();
         // First, create the short URL with an empty short code
         $shortUrl = new ShortUrl();
         $shortUrl->setOriginalUrl($url);
         $this->em->persist($shortUrl);
         $this->em->flush();
         // Generate the short code and persist it
         $shortCode = $this->convertAutoincrementIdToShortCode($shortUrl->getId());
         $shortUrl->setShortCode($shortCode)->setTags($this->tagNamesToEntities($this->em, $tags));
         $this->em->flush();
         $this->em->commit();
         return $shortCode;
     } catch (ORMException $e) {
         if ($this->em->getConnection()->isTransactionActive()) {
             $this->em->rollback();
             $this->em->close();
         }
         throw new RuntimeException('An error occurred while persisting the short URL', -1, $e);
     }
 }
コード例 #2
0
ファイル: UrlShortenerTest.php プロジェクト: shlinkio/shlink
 /**
  * @test
  */
 public function shortCodeIsProperlyParsed()
 {
     // 12C1c -> 10
     $shortCode = '12C1c';
     $shortUrl = new ShortUrl();
     $shortUrl->setShortCode($shortCode)->setOriginalUrl('expected_url');
     $repo = $this->prophesize(ObjectRepository::class);
     $repo->findOneBy(['shortCode' => $shortCode])->willReturn($shortUrl);
     $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal());
     $this->assertFalse($this->cache->contains($shortCode . '_longUrl'));
     $url = $this->urlShortener->shortCodeToUrl($shortCode);
     $this->assertEquals($shortUrl->getOriginalUrl(), $url);
     $this->assertTrue($this->cache->contains($shortCode . '_longUrl'));
 }