<?php declare(strict_types=1);


namespace Newland\NeosCommon\Utility;

use Doctrine\ORM\AbstractQuery;
use Neos\Cache\Frontend\FrontendInterface;
use Neos\Flow\Cache\CacheManager;

trait CacheAware
{

    /** @var FrontendInterface */
    protected $cache;

    abstract protected function cacheName(): string;

    public function injectCache(CacheManager $cacheManager): void
    {
        $this->cache = $cacheManager->getCache($this->cacheName());
    }

    /** @return mixed */
    protected function cache(string $key, callable $generator, int $lifetime = null, array $tags = [])
    {
        if ($this->cache->has($key)) {
            return $this->cache->get($key);
        }

        $result = $generator();
        $this->cache->set($key, $result, $tags, $lifetime);
        return $result;
    }

    protected function removeFromCache(string $key): void
    {
        $this->cache->remove($key);
    }

    protected function flushCache(): void
    {
        $this->cache->flush();
    }
}
