<?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\Writer\Apc;

use LifeStyle\Tools\CachingBundle\Api\Data\Writer\WriterInterface;
use Symfony\Component\HttpFoundation\Response;
use LifeStyle\Tools\CachingBundle\Api\Manager as ApiManager;

/**
 * Class Writer
 * @package LifeStyle\Tools\CachingBundle\Api\Data\Writer\Apc
 */
class Writer implements WriterInterface
{
    /**
     * @var ApiManager
     */
    protected $apiM;

    /**
     * CachingSubscriber constructor.
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
    }

    /**
     * Write the content of the current response into the cache using the given key and TTL
     *
     * @param Response $response
     * @param string $cacheKey
     * @param integer $cacheTTL
     */
    public function writeCache(Response $response, $cacheKey, $cacheTTL)
    {
        if (extension_loaded('apc')) {
            apc_store($cacheKey, serialize($response->getContent()), $cacheTTL);
            apc_store($cacheKey . "-status", serialize($response->getStatusCode()), $cacheTTL);
        }
    }

    /**
     * Write the content of the current response into the cache using the given key and TTL
     *
     * @param string $cacheKey
     * @param mixed $content
     * @param integer|null $cacheTTL
     */
    public function writeCacheByKey($cacheKey, $content, $cacheTTL = null)
    {
        if ($this->apiM->getConfig()->isCacheEnabled() && null !== $content) {
            if (null === $cacheTTL) {
                $cacheTTL = $this->apiM->getConfig()->getDefaultTtl();
            }
            if (extension_loaded('apc')) {
                apc_store($cacheKey, serialize($content), $cacheTTL);
            }
        }
    }

    /**
     * Clears the cache / deletes all stored content in the cache
     *
     * Takes no parameters and does not return any results
     */
    public function clearCache()
    {
        if (extension_loaded('apc')) {
            apc_clear_cache("user");
        }
    }
}
