<?php
namespace App\Service;
use Gregwar\Image\Image;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\KernelInterface;
class ImageCacheService
{
private $container;
public function __construct(KernelInterface $kernel, private readonly RequestStack $requestStack, private $projectRoot)
{
$this->container = $kernel->getContainer();
}
// fetch image or generate new depending on parameter provided
public function imageCache($pathtofile, $filter, $width = 0, $height = 0, $background = 'transparent')
{
// echo $this->projectRoot . '/public' . $pathtofile." - ".$filter." W=".$width." H=".$height."<br/>";
if (0 == $width || 0 == $height) {
echo '( Error: width or height not set )';
return false;
}
// echo getcwd().$this->container->getParameter('gregwar_image.fallback_image')."----";
$fallback = $this->container->getParameter('gregwar_image.fallback_image');
$pathtofile = is_file($this->projectRoot.'/public'.$pathtofile) ? $this->projectRoot.'/public'.$pathtofile : $this->projectRoot.'/public'.$fallback;
$pathtofile = str_replace('\\', '/', (string) $pathtofile);
$file = explode('/', $pathtofile);
$filename = end($file);
$folder = $file[count($file) - 2];
$folder .= '/'.$width.'x'.$height;
$cacheDir = $this->projectRoot.'/public/userfiles/image_cache/'.$folder;
$extArray = explode('.', $filename);
$ext = strtolower(end($extArray));
// default to jpg 80%
$method = 'guess';
$param = 80;
// Check Browser Supports WebP - Currently Chrome/Edge/Android
if ($this->isSupported(
$this->requestStack->getCurrentRequest()->headers->get('User-Agent')
)) {
$method = 'webp';
$param = 100;
}
// if webp isnt supported and the image is png we need to run
// png function to preserve transparancy
if ('guess' === $method && 'png' == $ext) {
$method = 'png';
}
$generateFile = match (strtolower((string) $filter)) {
'scaleresize' => Image::open($pathtofile)->scaleResize($width, $height)->fixOrientation()
->setCacheDir($cacheDir.'-sr')
->setPrettyName($filename, false)->{$method}($param),
'cropresize' => Image::open($pathtofile)->cropResize($width, $height)->fixOrientation()
->setCacheDir($cacheDir.'-cr')
->setPrettyName($filename, false)->{$method}($param),
'zoomcrop' => Image::open($pathtofile)->zoomCrop($width, $height)->fixOrientation()
->setCacheDir($cacheDir.'-zc')
->setPrettyName($filename, false)->{$method}($param),
default => Image::open($pathtofile)->scaleResize($width, $height)->fixOrientation()
->setCacheDir($cacheDir.'-sr')
->setPrettyName($filename, false)->{$method}($param),
};
return str_replace(getcwd(), '', (string) $generateFile);
}
private function isSupported($agent)
{
$known_good = [
'Chrome',
'Android',
];
foreach ($known_good as $good) {
if (str_contains((string) $agent, $good)) {
return true;
}
}
return false;
}
}