<?php

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

namespace Newland\Toubiz\Poi\Neos\Service;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cache\CacheManager;

class CacheService
{
    /**
     * @var CacheManager
     * @Flow\Inject
     */
    protected $cacheManager;

    /**
     * @var string
     */
    protected $cacheName = '';

    public function setCacheName(string $cacheName)
    {
        $this->cacheName = $cacheName;
    }

    public function get(string $key, string $hash)
    {
        try {
            $entry = $this->cacheManager->getCache($this->cacheName)->get($key);
            if ($entry['hash'] !== $hash) {
                return null;
            }

            return $entry['value'];
        } catch (\Exception $e) {
            return null;
        }
    }

    public function set(string $key, $value, string $hash)
    {
        $cache = $this->cacheManager->getCache($this->cacheName);
        $cache->set(
            $key,
            [
                'hash' => $hash,
                'value' => $value,
            ]
        );
    }
}
