Skip to content

Instantly share code, notes, and snippets.

@edhaase
Created January 15, 2016 18:08
Show Gist options
  • Save edhaase/de32eeba7de6e8e01d99 to your computer and use it in GitHub Desktop.
Save edhaase/de32eeba7de6e8e01d99 to your computer and use it in GitHub Desktop.
<?php
/**
* This one leverages include with a data uri. Can't leverage opcache with it, but
* for those of you with a religious fear of eval, this is an alternative.
*
* Requires allow_url_include to be enabled in php.ini
*/
class TwigDataUriStashCache implements \Twig_CacheInterface
{
private $pool;
public function __construct(\Stash\Interfaces\PoolInterface $pool)
{
$this->pool = $pool;
}
/**
* {@inheritdoc}
*/
public function generateKey($name, $className)
{
$key = "$name;$className";
// Key generation can be tweaked, it doesn't need to be cryptographically secure
// Just fast.
$key = "TWIG_CACHE;" . hash_hmac('sha256', $key, 'TWIG', false);
return $key;
}
/**
* {@inheritdoc}
*/
public function write($key, $content)
{
$item = $this->pool->getItem($key);
$item->set([
'data' => 'data://text/plain;base64,' . base64_encode($content),
'timestamp' => time()
]);
}
/**
* {@inheritdoc}
*/
public function load($key)
{
$item = $this->pool->getItem($key);
$content = $item->get();
if(!$item->isMiss()) {
@include ($content['data']);
}
}
/**
* {@inheritdoc}
*/
public function getTimestamp($key)
{
$item = $this->pool->getItem($key);
$content = $item->get();
if(!$item->isMiss()) {
return $content['timestamp'];
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment