<?php
namespace Aqarmap\Bundle\ListingBundle\EventListener;
use Aqarmap\Bundle\ListingBundle\Entity\ListingPhoto;
use Aqarmap\Bundle\ListingBundle\Entity\Photo;
use Aqarmap\Bundle\MainBundle\Service\ThumbURL;
use JMS\Serializer\EventDispatcher\Events;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
/**
* Add thumbs url pre serialization.
*/
class PhotoThumbSerializerListener implements EventSubscriberInterface
{
private $thumbURL;
private $uploaderHelper;
public function __construct(ThumbURL $thumbURL, UploaderHelper $uploaderHelper)
{
$this->thumbURL = $thumbURL;
$this->uploaderHelper = $uploaderHelper;
}
public static function getSubscribedEvents()
{
return [
[
'event' => Events::PRE_SERIALIZE,
'method' => 'onPreSerialize',
'class' => Photo::class,
],
[
'event' => Events::PRE_SERIALIZE,
'method' => 'onPreSerialize',
'class' => ListingPhoto::class,
],
];
}
public function onPreSerialize(PreSerializeEvent $event): void
{
$object = $event->getObject();
if ($object instanceof ListingPhoto) {
$hasValidLogo = $object->getListing()->getUser()->getIsValidLogo();
$logo = $object->getListing()->getUser()->getLogo();
$this->generateThumbnailsUrls($object->getFile(), $hasValidLogo ? $logo : null);
} elseif ($object instanceof Photo) {
if ($object->getThumbnails()) {
return;
}
$this->generateThumbnailsUrls($object);
}
}
private function generateThumbnailsUrls(Photo $photo, ?Photo $logoPhoto = null)
{
$thumbsUrls = [
'large' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'large'),
'small' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'small'),
'thumb' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'search-thumb'),
'logo' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'logo'),
];
if ($logoPhoto) {
$largeWithLogo = $this->thumbURL->generateURL($this->uploaderHelper->asset($logoPhoto, 'file'), 'slider-photo-watermarked-logo-large');
$largeWithLogo .= '/'.ltrim($this->uploaderHelper->asset($photo, 'file'), '/');
$thumbsUrls['large'] = $largeWithLogo;
}
$photo->setThumbnails($thumbsUrls);
}
}