lib/composer/FileBundle/src/VisualMedia/FileBundle/Service/FileProvider.php line 46

Open in your IDE?
  1. <?php
  2. /**
  3. * File Provider
  4. *
  5. * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
  6. */
  7. namespace VisualMedia\FileBundle\Service;
  8. use Imagick;
  9. use Symfony\Component\DependencyInjection\ContainerInterface;
  10. use Symfony\Component\Filesystem\Filesystem;
  11. use Symfony\Component\HttpFoundation\File\File;
  12. use Symfony\Component\HttpFoundation\File\UploadedFile;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use VisualMedia\FileBundle\DependencyInjection\Configuration;
  15. use VisualMedia\FileBundle\Entity\BaseUpload;
  16. use VisualMedia\LisaBundle\Component\Interfaces\ServiceInterface;
  17. use VisualMedia\LisaBundle\Service\AssetHelper;
  18. /**
  19. * File Provider
  20. *
  21. * Service that handles all file uploading/downloading.
  22. */
  23. class FileProvider implements ServiceInterface
  24. {
  25. public const SERVICE_ID = 'visualmedia.lisa.file_provider';
  26. public const FRONTEND_PATH_REDIRECT = true;
  27. public const FALLBACK_IMAGE_SRC = ['build/bundles/lisa/images/image-placeholder.jpg'];
  28. public const FOLDER_PUBLIC = 'public';
  29. public const FOLDER_UPLOADS = 'uploads';
  30. /**
  31. * @var ContainerInterface
  32. */
  33. protected $container;
  34. /**
  35. * @param ContainerInterface $container
  36. */
  37. public function __construct(ContainerInterface $container, UrlGeneratorInterface $router)
  38. {
  39. $this->container = $container;
  40. $this->router = $router;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public static function getServiceId(): string
  46. {
  47. return static::SERVICE_ID;
  48. }
  49. /**
  50. * @return string
  51. */
  52. public function getFrontendUploadsFolder(): string
  53. {
  54. return sprintf('/%s', static::FOLDER_UPLOADS);
  55. }
  56. /**
  57. * @return string
  58. */
  59. public function getBackendUploadsFolder(): string
  60. {
  61. return sprintf('%s/%s/%s', $this->container->getParameter('kernel.project_dir'), static::FOLDER_PUBLIC, static::FOLDER_UPLOADS);
  62. }
  63. /**
  64. * @param BaseUpload $upload
  65. * @return string
  66. */
  67. public function getFrontendPath(?BaseUpload $upload): ?string
  68. {
  69. if ($upload === null || $upload->getid() === null) {
  70. return null;
  71. }
  72. $fileSystem = new Filesystem();
  73. if ($fileSystem->exists($this->getBackendPath($upload)) === false) {
  74. return null;
  75. }
  76. $modified = $upload->getUpdated()->getTimestamp();
  77. $filename = sprintf('%s.%s', $upload->getFilename(), $upload->getExtension());
  78. if (static::FRONTEND_PATH_REDIRECT) {
  79. $path = $this->router->generate('file', [
  80. 'filename' => $upload->getFilename(),
  81. 'extension' => $upload->getExtension()
  82. ]);
  83. }
  84. else {
  85. // Did not add router path because could not find a exemple were this if is false
  86. $path = sprintf('%s/%s/%s?m=%s', $this->getFrontendUploadsFolder(), $upload->getExtension(), $filename, $modified);
  87. }
  88. return $path;
  89. }
  90. /**
  91. * @param BaseUpload $upload
  92. * @param int $width
  93. * @param int $height
  94. * @return string
  95. */
  96. public function getCachedImageFrontendPath(?BaseUpload $upload, $width = null, $height = null): ?string
  97. {
  98. if ($upload === null || $upload->getid() === null) {
  99. return null;
  100. }
  101. $fileSystem = new Filesystem();
  102. if ($fileSystem->exists($this->getBackendPath($upload)) === false) {
  103. return null;
  104. }
  105. $backendPath = $this->getBackendPath($upload);
  106. [$originalWidth, $originalHeight] = getimagesize($backendPath) ?: [null, null];
  107. // Vector images.
  108. if ($originalWidth === null || $originalHeight === null) {
  109. return $this->router->generate('file', [
  110. 'filename' => $upload->getFilename(),
  111. 'extension' => $upload->getExtension(),
  112. ]);
  113. }
  114. $aspectRatio = $originalWidth / $originalHeight;
  115. $width = $width === null ? round($height * $aspectRatio) : $width;
  116. $height = $height === null ? round($width / $aspectRatio) : $height;
  117. $dimensions = sprintf('%sx%s', $width, $height);
  118. $path = $this->router->generate('image', [
  119. 'filename' => $upload->getFilename(),
  120. 'dimensions' => $dimensions,
  121. 'extension' => $upload->getExtension()
  122. ]);
  123. return $path;
  124. }
  125. /**
  126. * @param BaseUpload $entity
  127. * @return string
  128. */
  129. public function getBackendPath(?BaseUpload $upload): ?string
  130. {
  131. if ($upload === null) {
  132. return null;
  133. }
  134. $filename = sprintf('%s.%s', $upload->getFilename(), $upload->getExtension());
  135. $path = sprintf('%s/%s/%s', $this->getBackendUploadsFolder(), $upload->getExtension(), $filename);
  136. return $path;
  137. }
  138. /**
  139. * @param BaseUpload $upload
  140. * @param UploadedFile $file
  141. * @return void
  142. */
  143. public function store(BaseUpload $upload, UploadedFile $file): void
  144. {
  145. $backendUploadsFolder = $this->getBackendPath($upload);
  146. $exploded = explode('/', $backendUploadsFolder);
  147. $filename = array_pop($exploded);
  148. $path = implode('/', $exploded);
  149. $fs = new Filesystem();
  150. if (!$fs->exists($path)) {
  151. $fs->mkdir($path);
  152. }
  153. $file = $file->move($path, $filename);
  154. $mimeType = $file->getMimeType();
  155. if ($upload->isImage($mimeType)) {
  156. [$width, $height] = getimagesize($file) ?: [null, null];
  157. $limitWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_WIDTH));
  158. $limitHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_HEIGHT));
  159. $maxWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_WIDTH));
  160. $maxHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_HEIGHT));
  161. if (($width > $maxWidth && $limitWidth) || ($height > $maxHeight && $limitHeight)) {
  162. $this->resizeImageToMax($upload);
  163. }
  164. }
  165. }
  166. /**
  167. * @see https://packagist.org/packages/ps/image-optimizer.
  168. * @param string $sourceUrl
  169. * @param string $targetUrl
  170. * @param int $newWidth
  171. * @param int $newHeight
  172. * @return void
  173. */
  174. public function resizeImage(string $sourceUrl, string $targetUrl, int $newWidth, int $newHeight): void
  175. {
  176. $exploded = explode('.', $sourceUrl);
  177. $extension = array_pop($exploded);
  178. switch ($extension) {
  179. case 'png':
  180. $imagick = new Imagick(realpath($sourceUrl));
  181. $imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_UNDEFINED, 1);
  182. $imagick->writeImage($targetUrl);
  183. $minQuality = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_PNG_MIN));
  184. $maxQuality = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_PNG_MAX));
  185. // Only replace the image when pngquant is available and returned output;
  186. // otherwise the resized image would be overwritten with 0 bytes.
  187. $compressed = shell_exec(sprintf('pngquant --quality=%s-%s - < %s 2>/dev/null', $minQuality, $maxQuality, escapeshellarg($targetUrl)));
  188. if (is_string($compressed) && $compressed !== '') {
  189. file_put_contents($targetUrl, $compressed);
  190. }
  191. break;
  192. case 'gif':
  193. $imagick = new Imagick(realpath($sourceUrl));
  194. $imagick = $imagick->coalesceImages();
  195. do {
  196. $imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_BOX, 1);
  197. } while ($imagick->nextImage());
  198. $imagick = $imagick->deconstructImages();
  199. $imagick->writeImages($targetUrl, true);
  200. break;
  201. default:
  202. $imagick = new Imagick(realpath($sourceUrl));
  203. $imagick->resizeImage($newWidth, $newHeight, Imagick::FILTER_UNDEFINED, 1);
  204. $imagick->setImageCompression(Imagick::COMPRESSION_LOSSLESSJPEG);
  205. $imagick->setImageCompressionQuality($this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_COMPRESSION_QUALITY_JPEG)));
  206. $imagick->writeImage($targetUrl);
  207. break;
  208. }
  209. }
  210. /**
  211. * @param BaseUpload $upload
  212. * @return void
  213. */
  214. protected function resizeImageToMax(BaseUpload $upload): void
  215. {
  216. $backendPath = $this->getBackendPath($upload);
  217. $extension = $upload->getExtension();
  218. [$width, $height] = getimagesize($backendPath) ?: [null, null];
  219. $aspectRatio = $width / $height;
  220. $limitWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_WIDTH));
  221. $limitHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_LIMIT_HEIGHT));
  222. $maxWidth = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_WIDTH));
  223. $maxHeight = $this->container->getParameter(sprintf('%s.%s', Configuration::CONFIGKEY, Configuration::CONFIGKEY_MAX_HEIGHT));
  224. $maxWidth = $limitWidth ? $maxWidth : $width;
  225. $maxHeight = $limitHeight ? $maxHeight : $height;
  226. if ($width / $maxWidth > $height / $maxHeight) {
  227. list($newWidth, $newHeight) = array($maxWidth, (int)floor($maxWidth / $aspectRatio));
  228. }
  229. else {
  230. list($newHeight, $newWidth) = array($maxHeight, (int)floor($maxHeight * $aspectRatio));
  231. }
  232. $this->resizeImage($backendPath, $backendPath, $newWidth, $newHeight);
  233. }
  234. /**
  235. * @param BaseUpload $upload
  236. * @return void
  237. */
  238. public function remove(BaseUpload $upload): void
  239. {
  240. $backendPath = $this->getBackendPath($upload);
  241. $fileSystem = new Filesystem();
  242. if ($fileSystem->exists($backendPath)) {
  243. $fileSystem->remove($backendPath);
  244. }
  245. }
  246. /**
  247. * @return string
  248. */
  249. public function getFallbackImage(): ?string
  250. {
  251. $assetHelper = $this->container->get(AssetHelper::getServiceId());
  252. return $assetHelper->getUrl(...static::FALLBACK_IMAGE_SRC);
  253. }
  254. }