* @package Vhs * @subpackage ViewHelpers\Render */ class CacheViewHelper extends AbstractRenderViewHelper { const ID_PREFIX = 'vhs-render-cache-viewhelper'; const ID_SEPARATOR = '-'; /** * @var \TYPO3\CMS\Core\Cache\Frontend\StringFrontend */ protected $cache; /** * @return void */ public function initialize() { $cacheManager = isset($GLOBALS['typo3CacheManager']) ? $GLOBALS['typo3CacheManager'] : GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager'); $this->cache = $cacheManager->getCache('vhs_main'); } /** * Render * * @param mixed $identity Identifier for the cached content (usage preferred) * @param mixed $content Value to be cached * @return mixed * @throws \RuntimeException */ public function render($identity, $content = NULL) { if (FALSE === ctype_alnum(preg_replace('/[\-_]/i', '', $identity))) { if (TRUE === $identity instanceof DomainObjectInterface) { $identity = get_class($identity) . self::ID_SEPARATOR . $identity->getUid(); } elseif (TRUE === method_exists($identity, '__toString')) { $identity = (string) $identity; } else { throw new \RuntimeException( 'Parameter $identity for Render/CacheViewHelper was not a string or a string-convertible object', 1352581782 ); } } // Hash the cache-key to circumvent disallowed chars $identity = sha1($identity); if (TRUE === $this->has($identity)) { return $this->retrieve($identity); } if (NULL === $content) { $content = $this->renderChildren(); } $this->store($content, $identity); return $content; } /** * @param string $id * @return boolean */ protected function has($id) { return (boolean) $this->cache->has(self::ID_PREFIX . self::ID_SEPARATOR . $id); } /** * @param mixed $value * @param string $id * @return void */ protected function store($value, $id) { $this->cache->set(self::ID_PREFIX . self::ID_SEPARATOR . $id, $value); } /** * @param string $id * @return mixed */ protected function retrieve($id) { if ($this->cache->has(self::ID_PREFIX . self::ID_SEPARATOR . $id)) { return $this->cache->get(self::ID_PREFIX . self::ID_SEPARATOR . $id); } return NULL; } }