<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Utility;

use Neos\Cache\Frontend\FrontendInterface;
use Neos\Flow\Cache\CacheManager;
use Neos\Flow\Utility\Environment;
use Neos\Flow\Annotations as Flow;

class CacheUtility
{

    /**
     * @var Environment
     * @Flow\Inject()
     */
    protected $environment;

    /** @var FrontendInterface */
    protected $cache;
    public function injectCache(CacheManager $cacheManager): void
    {
        $this->cache = $cacheManager->getCache('Newland_ToubizWidgetRendering-Ssr');
    }

    public function cacheOrGenerate(string $key, callable $generator): string
    {
        if ($this->environment->getContext()->isDevelopment()) {
            return $generator();
        }

        if ($this->cache->has($key)) {
            return $this->cache->get($key);
        }

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

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