Skip to content

Commit

Permalink
Store given fragment into cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
hkp22 committed Sep 19, 2018
1 parent b9448ad commit c0a249c
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/FragmentCaching.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace Hkp22\CacheLaraViewFragments;

use Illuminate\Contracts\Cache\Repository as Cache;

class FragmentCaching
{
/**
* The cache repository.
*
* @var Cache
*/
protected $cache;

/**
* Create a new class instance.
*
* @param Cache $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}

/**
* Put to the cache.
*
* @param mixed $key
* @param string $fragment
*/
public function put($key, $fragment)
{
$key = $this->normalizeCacheKey($key);

return $this->cache
->tags('views')
->rememberForever($key, function () use ($fragment) {
return $fragment;
});
}

/**
* Check if the given key exists in the cache.
*
* @param mixed $key
*/
public function has($key)
{
$key = $this->normalizeCacheKey($key);

return $this->cache
->tags('views')
->has($key);
}

/**
* Normalize the cache key.
*
* @param mixed $key
*/
protected function normalizeCacheKey($key)
{
if (is_object($key) && method_exists($key, 'getCacheKey')) {
return $key->getCacheKey();
}

return $key;
}
}
25 changes: 25 additions & 0 deletions tests/FragmentCachingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Hkp22\Tests\CacheLaraViewFragments;

use Hkp22\CacheLaraViewFragments\FragmentCaching;
use Hkp22\Tests\CacheLaraViewFragments\Stubs\Models\Post;

class FragmentCachingTest extends TestCase
{
/** @test */
public function it_caches_the_given_key()
{
$post = $this->makePost();

$cache = new \Illuminate\Cache\Repository(
new \Illuminate\Cache\ArrayStore
);
$cache = new FragmentCaching($cache);

$cache->put($post->getCacheKey(), '<div>view fragment</div>');

$this->assertTrue($cache->has($post->getCacheKey()));
$this->assertTrue($cache->has($post));
}
}

0 comments on commit c0a249c

Please sign in to comment.