<?php
/**
* @author Lezhnev Maxim <info@mldev.ru>
* @copyright 2019
*/
namespace MLDev\BaseBundle\Imagine;
use Imagine\Image\ImagineInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class CacheManager
* @package MLDev\BaseBundle\Imagine
*/
class CacheManager
{
/**
* @var string
*/
private $webRoot;
/**
* @var Request
*/
private $request;
/**
* @var ImagineInterface
*/
private $imagine;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var CacheResolver
*/
private $cacheResolver;
/**
* @var FilterManager
*/
private $filterManager;
/**
* CacheManager constructor.
*
* @param RequestStack $request
* @param Filesystem $filesystem
* @param ImagineInterface $imagine
* @param CacheResolver $cacheResolver
* @param FilterManager $filterManager
* @param string $publicDir
*/
public function __construct(
RequestStack $request,
Filesystem $filesystem,
ImagineInterface $imagine,
CacheResolver $cacheResolver,
FilterManager $filterManager,
string $publicDir
)
{
$this->request = $request->getCurrentRequest();
$this->imagine = $imagine;
$this->filesystem = $filesystem;
$this->cacheResolver = $cacheResolver;
$this->filterManager = $filterManager;
$this->publicDir = $publicDir;
}
/**
* Forces image caching and returns path to cached image.
*
* @param string $path
* @param string $filter
* @param array $options
*
* @return string|null
*/
public function cacheImage($path, $filter, $options = [])
{
/** @var string $basePath */
$basePath = $this->request->getBaseUrl();
$path = '/' . ltrim($path, '/');
// @TODO: find out why I need double urldecode to get a valid path
$browserPath = urldecode(
urldecode(
$this->cacheResolver->getBrowserPath($path, $filter, $options)
)
);
if (!empty($basePath) && 0 === strpos($browserPath, $basePath)) {
$browserPath = substr($browserPath, strlen($basePath));
}
// // if cache path cannot be determined, return 404
if (null === $browserPath) {
return $path;
}
$realPath = realpath($this->publicDir) . $browserPath;
$sourcePath = realpath($this->publicDir) . $path;
// if the file has already been cached, just return path
if (file_exists($realPath)) {
return $browserPath;
}
if (!file_exists($sourcePath)) {
return $path;
}
$dir = pathinfo($realPath, PATHINFO_DIRNAME);
if (!is_dir($dir)) {
if (false === $this->filesystem->mkdir($dir)) {
throw new \RuntimeException(sprintf(
'Could not create directory %s', $dir
));
}
}
// TODO: get rid of hard-coded quality and format
$this->filterManager->getFilter($filter, $options)
->apply($this->imagine->open($sourcePath))
->save($realPath, array(
'quality' => $this->filterManager->getOption($filter, "quality", 100),
'format' => $this->filterManager->getOption($filter, "format", null)
));
return $browserPath;
}
}