<?php
/**
* File Provider
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
*/
namespace VisualMedia\FileBundle\Service;
use Imagick;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use VisualMedia\FileBundle\DependencyInjection\Configuration;
use VisualMedia\FileBundle\Entity\BaseUpload;
use VisualMedia\LisaBundle\Component\Interfaces\ServiceInterface;
use VisualMedia\LisaBundle\Service\AssetHelper;
/**
* File Provider
*
* Service that handles all file uploading/downloading.
*/
class FileProvider implements ServiceInterface
{
public const SERVICE_ID = 'visualmedia.lisa.file_provider';
public const FRONTEND_PATH_REDIRECT = true;
public const FALLBACK_IMAGE_SRC = ['build/bundles/lisa/images/image-placeholder.jpg'];
public const FOLDER_PUBLIC = 'public';
public const FOLDER_UPLOADS = 'uploads';
/**
* @var ContainerInterface
*/
protected $container;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container, UrlGeneratorInterface $router)
{
$this->container = $container;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public static function getServiceId(): string
{
return static::SERVICE_ID;
}
/**
* @return string
*/
public function getFrontendUploadsFolder(): string
{
return sprintf('/%s', static::FOLDER_UPLOADS);
}
/**
* @return string
*/
public function getBackendUploadsFolder(): string
{
return sprintf('%s/%s/%s', $this->container->getParameter('kernel.project_dir'), static::FOLDER_PUBLIC, static::FOLDER_UPLOADS);
}
/**
* @param BaseUpload $upload
* @return string
*/
public function getFrontendPath(?BaseUpload $upload): ?string
{
if ($upload === null || $upload->getid() === null) {
return null;
}
$fileSystem = new Filesystem();
if ($fileSystem->exists($this->getBackendPath($upload)) === false) {
return null;
}
$modified = $upload->getUpdated()->getTimestamp();
$filename = sprintf('%s.%s', $upload->getFilename(), $upload->getExtension());
if (static::FRONTEND_PATH_REDIRECT) {
$path = $this->router->generate('file', [
'filename' => $upload->getFilename(),
'extension' => $upload->getExtension()
]);
}
else {
// Did not add router path because could not find a exemple were this if is false
$path = sprintf('%s/%s/%s?m=%s', $this->getFrontendUploadsFolder(), $upload->getExtension(), $filename, $modified);
}
return $path;
}
/**
* @param BaseUpload $upload
* @param int $width
* @param int $height
* @return string
*/
public function getCachedImageFrontendPath(?BaseUpload $upload, $width = null, $height = null): ?string
{
if ($upload === null || $upload->getid() === null) {
return null;
}
$fileSystem = new Filesystem();
if ($fileSystem->exists($this->getBackendPath($upload)) === false) {
return null;
}
$backendPath = $this->getBackendPath($upload);
[$originalWidth, $originalHeight] = getimagesize($backendPath) ?: [null, null];
// Vector images.
if ($originalWidth === null || $originalHeight === null) {
return $this->router->generate('file', [
'filename' => $upload->getFilename(),
'extension' => $upload->getExtension(),
]);
}
$aspectRatio = $originalWidth / $originalHeight;
$width = $width === null ? round($height * $aspectRatio) : $width;
$height = $height === null ? round($width / $aspectRatio) : $height;
$dimensions = sprintf('%sx%s', $width, $height);
$path = $this->router->generate('image', [
'filename' => $upload->getFilename(),
'dimensions' => $dimensions,
'extension' => $upload->getExtension()
]);
return $path;
}
/**
* @param BaseUpload $entity
* @return string
*/
public function getBackendPath(?BaseUpload $upload): ?string
{
if ($upload === null) {
return null;
}
$filename = sprintf('%s.%s', $upload->getFilename(), $upload->getExtension());
$path = sprintf('%s/%s/%s', $this->getBackendUploadsFolder(), $upload->getExtension(), $filename);
return $path;
}
/**
* @param BaseUpload $upload
* @param UploadedFile $file
* @return void
*/
public function store(BaseUpload $upload, UploadedFile $file): void
{
$backendUploadsFolder = $this->getBackendPath($upload);
$exploded = explode('/', $backendUploadsFolder);
$filename = array_pop($exploded);
$path = implode('/', $exploded);
$fs = new Filesystem();
if (!$fs->exists($path)) {
$fs->mkdir($path);
}
$file = $file->move($path, $filename);
$mimeType = $file->getMimeType();
if ($upload->isImage($mimeType)) {
[$width, $height] = getimagesize($file) ?: [null, null];
$limitWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_WIDTH));
$limitHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_HEIGHT));
$maxWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_WIDTH));
$maxHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_HEIGHT));
if (($width > $maxWidth && $limitWidth) || ($height > $maxHeight && $limitHeight)) {
$this->resizeImageToMax($upload);
}
}
}
/**
* @see https://packagist.org/packages/ps/image-optimizer.
* @param string $sourceUrl
* @param string $targetUrl
* @param int $newWidth
* @param int $newHeight
* @return void
*/
public function resizeImage(string $sourceUrl, string $targetUrl, int $newWidth, int $newHeight): void
{
$exploded = explode('.', $sourceUrl);
$extension = array_pop($exploded);
switch ($extension) {
case 'png':
$imagick = new Imagick(realpath($sourceUrl));
$imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_UNDEFINED, 1);
$imagick->writeImage($targetUrl);
$minQuality = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_PNG_MIN));
$maxQuality = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_PNG_MAX));
// Only replace the image when pngquant is available and returned output;
// otherwise the resized image would be overwritten with 0 bytes.
$compressed = shell_exec(sprintf('pngquant --quality=%s-%s - < %s 2>/dev/null', $minQuality, $maxQuality, escapeshellarg($targetUrl)));
if (is_string($compressed) && $compressed !== '') {
file_put_contents($targetUrl, $compressed);
}
break;
case 'gif':
$imagick = new Imagick(realpath($sourceUrl));
$imagick = $imagick->coalesceImages();
do {
$imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_BOX, 1);
} while ($imagick->nextImage());
$imagick = $imagick->deconstructImages();
$imagick->writeImages($targetUrl, true);
break;
default:
$imagick = new Imagick(realpath($sourceUrl));
$imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_UNDEFINED, 1);
$imagick->setImageCompression(Imagick::COMPRESSION_LOSSLESSJPEG);
$imagick->setImageCompressionQuality($this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_JPEG)));
$imagick->writeImage($targetUrl);
break;
}
}
/**
* @param BaseUpload $upload
* @return void
*/
protected function resizeImageToMax(BaseUpload $upload): void
{
$backendPath = $this->getBackendPath($upload);
$extension = $upload->getExtension();
[$width, $height] = getimagesize($backendPath) ?: [null, null];
$aspectRatio = $width / $height;
$limitWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_WIDTH));
$limitHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_HEIGHT));
$maxWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_WIDTH));
$maxHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_HEIGHT));
$maxWidth = $limitWidth ? $maxWidth : $width;
$maxHeight = $limitHeight ? $maxHeight : $height;
if ($width / $maxWidth > $height / $maxHeight) {
list($newWidth, $newHeight) = array($maxWidth, (int)floor($maxWidth / $aspectRatio));
}
else {
list($newHeight, $newWidth) = array($maxHeight, (int)floor($maxHeight * $aspectRatio));
}
$this->resizeImage($backendPath, $backendPath, $newWidth, $newHeight);
}
/**
* @param BaseUpload $upload
* @return void
*/
public function remove(BaseUpload $upload): void
{
$backendPath = $this->getBackendPath($upload);
$fileSystem = new Filesystem();
if ($fileSystem->exists($backendPath)) {
$fileSystem->remove($backendPath);
}
}
/**
* @return string
*/
public function getFallbackImage(): ?string
{
$assetHelper = $this->container->get(AssetHelper::getServiceId());
return $assetHelper->getUrl(...static::FALLBACK_IMAGE_SRC);
}
}