Skip to content

Instantly share code, notes, and snippets.

@umpirsky
Created November 10, 2012 10:51
Show Gist options
  • Save umpirsky/4050717 to your computer and use it in GitHub Desktop.
Save umpirsky/4050717 to your computer and use it in GitHub Desktop.
<?php
namespace Avalanche\Bundle\ImagineBundle\Imagine;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Imagine cache manager.
*
* @author Саша Стаменковић <[email protected]>
*/
class CacheManager extends ContainerAware
{
/**
* Forces image caching and returns path to cached image.
*
* @param string $path
* @param string $filter
*
* @return string
*/
public function cacheImage($path, $filter)
{
$sourcePath = $this->container->getParameter('imagine.root_path').$path;
if (null === $filter) {
return $sourcePath;
}
//TODO: find out why I need double urldecode to get a valid path
$browserPath = urldecode(urldecode($this->container->get('imagine.cache.path.resolver')->getBrowserPath($path, $filter)));
$basePath = $this->container->get('request')->getBaseUrl();
if (!empty($basePath) && 0 === strpos($browserPath, $basePath)) {
$browserPath = substr($browserPath, strlen($basePath));
}
// if cache path cannot be determined, return 404
if (null === $browserPath) {
throw new NotFoundHttpException('Image doesn\'t exist');
}
$cachedPath = $this->container->getParameter('imagine.root_path').$browserPath;
// if the file has already been cached, we're probably not rewriting
// correctly, hence make a 301 to proper location, so browser remembers
if (file_exists($cachedPath)) {
return $cachedPath;
}
if (!file_exists($sourcePath)) {
throw new NotFoundHttpException(sprintf(
'Source image not found in "%s"', $sourcePath
));
}
$dir = pathinfo($cachedPath, PATHINFO_DIRNAME);
if (!is_dir($dir)) {
if (false === $this->container->get('filesystem')->mkdir($dir)) {
throw new \RuntimeException(sprintf(
'Could not create directory %s', $dir
));
}
}
// TODO: get rid of hard-coded quality and format
$this->container->get('imagine.filter.manager')->get($filter)
->apply($this->container->get('imagine')->open($sourcePath))
->save($cachedPath, array('quality' => $this->container->get('imagine.filter.manager')->getOption($filter, 'quality', 100)))
;
return $cachedPath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment