Updated UrlShortener to namespace the cache entries

This commit is contained in:
Alejandro Celaya 2016-08-09 13:32:33 +02:00
parent 99b7c77997
commit 8eb279fd28
2 changed files with 7 additions and 6 deletions

View file

@ -148,9 +148,10 @@ class UrlShortener implements UrlShortenerInterface
*/ */
public function shortCodeToUrl($shortCode) public function shortCodeToUrl($shortCode)
{ {
$cacheKey = sprintf('%s_longUrl', $shortCode);
// Check if the short code => URL map is already cached // Check if the short code => URL map is already cached
if ($this->cache->contains($shortCode)) { if ($this->cache->contains($cacheKey)) {
return $this->cache->fetch($shortCode); return $this->cache->fetch($cacheKey);
} }
// Validate short code format // Validate short code format
@ -165,7 +166,7 @@ class UrlShortener implements UrlShortenerInterface
// Cache the shortcode // Cache the shortcode
if (isset($shortUrl)) { if (isset($shortUrl)) {
$url = $shortUrl->getOriginalUrl(); $url = $shortUrl->getOriginalUrl();
$this->cache->save($shortCode, $url); $this->cache->save($cacheKey, $url);
return $url; return $url;
} }

View file

@ -129,10 +129,10 @@ class UrlShortenerTest extends TestCase
$repo->findOneBy(['shortCode' => $shortCode])->willReturn($shortUrl); $repo->findOneBy(['shortCode' => $shortCode])->willReturn($shortUrl);
$this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal()); $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal());
$this->assertFalse($this->cache->contains($shortCode)); $this->assertFalse($this->cache->contains($shortCode . '_longUrl'));
$url = $this->urlShortener->shortCodeToUrl($shortCode); $url = $this->urlShortener->shortCodeToUrl($shortCode);
$this->assertEquals($shortUrl->getOriginalUrl(), $url); $this->assertEquals($shortUrl->getOriginalUrl(), $url);
$this->assertTrue($this->cache->contains($shortCode)); $this->assertTrue($this->cache->contains($shortCode . '_longUrl'));
} }
/** /**
@ -151,7 +151,7 @@ class UrlShortenerTest extends TestCase
{ {
$shortCode = '12C1c'; $shortCode = '12C1c';
$expectedUrl = 'expected_url'; $expectedUrl = 'expected_url';
$this->cache->save($shortCode, $expectedUrl); $this->cache->save($shortCode . '_longUrl', $expectedUrl);
$this->em->getRepository(ShortUrl::class)->willReturn(null)->shouldBeCalledTimes(0); $this->em->getRepository(ShortUrl::class)->willReturn(null)->shouldBeCalledTimes(0);
$url = $this->urlShortener->shortCodeToUrl($shortCode); $url = $this->urlShortener->shortCodeToUrl($shortCode);