HummingBirdAnimeClient/src/AnimeClient/API/CacheTrait.php

99 lines
2.0 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
*
* PHP version 7.4
*
2017-02-15 16:13:32 -05:00
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
2020-01-08 15:39:49 -05:00
* @copyright 2015 - 2020 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-08-04 09:30:21 -04:00
* @version 5.1
* @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
* @param array $primeArgs
* @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;
}
/**
* Generate a hash as a cache key from the current method call
*
* @param mixed $object
* @param string $method
* @param array $args
* @return string
*/
public function getHashForMethodCall($object, string $method, array $args = []): string
{
$keyObj = [
2020-05-08 19:15:21 -04:00
'class' => get_class($object),
'method' => $method,
'args' => $args,
];
return sha1(json_encode($keyObj));
}
}