<?php
/**
* Twig Upload Url
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
*/
namespace VisualMedia\LisaBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use VisualMedia\FileBundle\Entity\BaseUpload;
use VisualMedia\FileBundle\Service\FileProvider;
/**
* Twig Upload Url
*/
class TwigUploadUrl extends AbstractExtension
{
public const ALWAYS_PLACEHOLDER = false;
/**
* @var FileProvider
*/
protected $fileProvider;
/**
* @param FileProvider $fileProvider
*/
public function __construct(FileProvider $fileProvider = null)
{
$this->fileProvider = $fileProvider;
}
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new TwigFilter('url', array($this, 'url')),
new TwigFilter('size', array($this, 'size')),
];
}
/**
* @param BaseUpload $upload
* @param array $options
* @return string
*
* Moved the resized image src logic to the upload model.
*/
public function url(?BaseUpload $upload, array $options = array()): string
{
if (!$upload) {
return $this->fileProvider->getFallbackImage();
}
return $upload->getResizedSrc($options);
}
/**
* @param BaseUpload $upload
* @return array
*/
public function size(?BaseUpload $upload): array
{
if (!$this->fileProvider) {
return [];
}
$url = $this->fileProvider->getBackendPath($upload) ?? $this->fileProvider->getFallbackImage();
[$width, $height] = @getimagesize($url) ?: [null, null];
return array(
'width' => $width,
'height' => $height,
);
}
}