public function storeInCache(EventInterface $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
$model = $response->getModel();
if (!$model instanceof Image || $this->cacheHit) {
// Only store images in the cache, and don't try to rewrite on cache hit
return;
}
$path = $this->getCacheFilePath($request);
$dir = dirname($path);
// Prepare data for the data
$data = serialize(['image' => $model, 'headers' => $response->headers]);
// Create directory if it does not already exist. The last is_dir is there because race
// conditions can occur, and another process could already have created the directory after
// the first is_dir($dir) is called, causing the mkdir() to fail, and as a result of that
// the image would not be stored in the cache. The error supressing is ghetto, I know, but
// thats how we be rolling.
//
// "What?! Did you forget to is_dir()-guard it?" - Mats Lindh
if (is_dir($dir) || @mkdir($dir, 0775, true) || is_dir($dir)) {
$tmpPath = $path . '.tmp';
// If in the middle of a cache write operation, fall back
if (file_exists($tmpPath) || file_exists($path)) {
return;
}
// Write the transformed image to a temporary location
if (file_put_contents($tmpPath, $data)) {
// Move the transformed image to the correct destination
// We have to silence this in case race-conditions lead to source not existing,
// in which case it'll give a warning (we'd use try/catch here in case of PHP7)
if (@rename($path . '.tmp', $path) === false && !file_exists($path)) {
throw new StorageException('An error occured while moving transformed image to cache');
}
}
}
}