<?php
namespace App\Controller;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\DataObject\OnixProduct;
use Pimcore\Model\WebsiteSetting;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
class ThumbnailController extends FrontendController
{
#[Route(
'/generate/{ean}-{size}',
name: 'edition_thumbnail',
requirements: ['ean' => '\\d+', 'size' => 'lg|md|xs'],
methods: ['GET']
)]
public function __invoke(string $ean, string $size): Response
{
$edition = OnixProduct::getByEan($ean, ['limit' => 1]);
if (empty($edition)) {
throw new NotFoundHttpException('Edition not found');
}
$relativePath = $edition->getItemThumbnail($size);
if ($relativePath === '' || $relativePath === null) {
$defaultPath = $this->getDefaultBookImagePath();
if ($defaultPath !== null) {
return new RedirectResponse($defaultPath);
}
throw new NotFoundHttpException('Thumbnail not available');
}
$filePath = $relativePath[0] === '/' ? PIMCORE_WEB_ROOT . $relativePath : $relativePath;
if (!is_file($filePath)) {
$defaultPath = $this->getDefaultBookImagePath();
if ($defaultPath !== null) {
return new RedirectResponse($defaultPath);
}
throw new NotFoundHttpException('Thumbnail file missing');
}
$response = new BinaryFileResponse($filePath);
$response->headers->set('Content-Type', 'image/webp');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
sprintf('%s-%s.webp', $ean, $size)
);
$response->setPublic();
$response->setMaxAge(86400);
return $response;
}
private function getDefaultBookImagePath(): ?string
{
$defaultSetting = WebsiteSetting::getByName('defaultImageBook');
if ($defaultSetting === null) {
return null;
}
$imageDefault = $defaultSetting->getData();
if ($imageDefault === null || !method_exists($imageDefault, 'getFullPath')) {
return null;
}
$path = $imageDefault->getFullPath();
return $path !== '' ? $path : null;
}
}