<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\CachingBundle\Api\Data\Reader\Apcu;

use Symfony\Component\HttpFoundation\Request;
use LifeStyle\Tools\CachingBundle\Api\Data\Reader\ReaderBase;
use LifeStyle\Tools\CachingBundle\Api\Data\Reader\ReaderResponse;

/**
 * Class Reader
 * @package LifeStyle\Tools\CachingBundle\Api\Data\Reader\Apcu
 */
class Reader extends ReaderBase
{
    /**
     * Get the cached content (if there is any) from the used caching engine / backend, put it into the
     * original request object and set up the cache read response object
     *
     * @param ReaderResponse $readerResponse
     * @param Request $request
     * @param string $cacheKey
     * @return ReaderResponse
     */
    protected function fetchCachedContent(ReaderResponse $readerResponse, Request $request, $cacheKey)
    {
        if (extension_loaded('apcu')) {
            if (apcu_exists($cacheKey)) {
                $cachedContent = unserialize(apcu_fetch($cacheKey));
                $cachedContent = $this->replaceScriptTime($cachedContent, $request->attributes->get('_format', 'json'));

                $request->attributes->set('_cachedContent', $cachedContent);
                $request->attributes->set('_statusCode', unserialize(apcu_fetch($cacheKey . "-status")));
                $request->attributes->set('_cacheKey', $cacheKey);
            } else {
                $readerResponse->setBuildCache(true);
            }
        }

        $readerResponse->setRequest($request);
        return $readerResponse;
    }

    /**
     * Get the cached content (if there is any) from the used caching engine / backend
     * @param string $cacheKey
     * @return mixed|null
     */
    protected function fetchCachedContentByKey($cacheKey)
    {
        if (extension_loaded('apcu') && apcu_exists($cacheKey)) {
            return unserialize(apcu_fetch($cacheKey));
        }
        return null;
    }
}
