HummingBirdAnimeClient/src/AnimeClient/API/CacheTrait.php

81 lines
1.6 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
/**
2017-02-15 16:13:32 -05:00
* Hummingbird Anime List Client
*
2018-08-22 13:48:27 -04:00
* An API client for Kitsu to manage anime and manga watch lists
*
2020-12-10 17:06:50 -05:00
* PHP version 7.4+
*
2017-02-15 16:13:32 -05:00
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
2021-01-13 01:52:03 -05:00
* @copyright 2015 - 2021 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-12-10 17:06:50 -05:00
* @version 5.2
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
2020-05-08 19:15:21 -04:00
use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\InvalidArgumentException;
/**
* Helper methods for dealing with the Cache
*/
trait CacheTrait {
/**
2020-05-08 19:15:21 -04:00
* @var CacheInterface
*/
2020-05-08 19:15:21 -04:00
protected CacheInterface $cache;
/**
* Inject the cache object
*
2020-05-08 19:15:21 -04:00
* @param CacheInterface $cache
* @return $this
*/
2020-05-08 19:15:21 -04:00
public function setCache(CacheInterface $cache): self
{
$this->cache = $cache;
return $this;
}
2017-01-16 11:26:19 -05:00
/**
* Get the cache object if it exists
*
2020-05-08 19:15:21 -04:00
* @return CacheInterface
2017-01-16 11:26:19 -05:00
*/
2020-05-08 19:15:21 -04:00
public function getCache(): CacheInterface
2017-01-16 11:26:19 -05:00
{
return $this->cache;
}
2020-05-08 19:15:21 -04:00
/**
* Get the cached value if it exists, otherwise set the cache value
* and return it.
*
* @param string $key
* @param callable $primer
2020-10-21 18:12:22 -04:00
* @param array|null $primeArgs
2020-05-08 19:15:21 -04:00
* @return mixed|null
* @throws InvalidArgumentException
*/
public function getCached(string $key, callable $primer, ?array $primeArgs = [])
{
$value = $this->cache->get($key, NULL);
if ($value === NULL)
{
$value = $primer(...$primeArgs);
if ($value === NULL)
{
return NULL;
}
$this->cache->set($key, $value);
}
return $value;
}
}