src/Aqarmap/Bundle/ListingBundle/EventListener/PhotoThumbSerializerListener.php line 57

  1. <?php
  2. namespace Aqarmap\Bundle\ListingBundle\EventListener;
  3. use Aqarmap\Bundle\ListingBundle\Entity\ListingPhoto;
  4. use Aqarmap\Bundle\ListingBundle\Entity\Photo;
  5. use Aqarmap\Bundle\MainBundle\Service\ThumbURL;
  6. use JMS\Serializer\EventDispatcher\Events;
  7. use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
  8. use JMS\Serializer\EventDispatcher\PreSerializeEvent;
  9. use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
  10. /**
  11. * Add thumbs url pre serialization.
  12. */
  13. class PhotoThumbSerializerListener implements EventSubscriberInterface
  14. {
  15. public function __construct(private readonly ThumbURL $thumbURL, private readonly UploaderHelper $uploaderHelper)
  16. {
  17. }
  18. public static function getSubscribedEvents()
  19. {
  20. return [
  21. [
  22. 'event' => Events::PRE_SERIALIZE,
  23. 'method' => 'onPreSerialize',
  24. 'class' => Photo::class,
  25. ],
  26. [
  27. 'event' => Events::PRE_SERIALIZE,
  28. 'method' => 'onPreSerialize',
  29. 'class' => ListingPhoto::class,
  30. ],
  31. ];
  32. }
  33. public function onPreSerialize(PreSerializeEvent $event): void
  34. {
  35. $object = $event->getObject();
  36. if ($object instanceof ListingPhoto) {
  37. $hasValidLogo = $object->getListing()->getUser()->getIsValidLogo();
  38. $logo = $object->getListing()->getUser()->getLogo();
  39. $this->generateThumbnailsUrls($object->getFile(), $hasValidLogo ? $logo : null);
  40. } elseif ($object instanceof Photo) {
  41. if ($object->getThumbnails()) {
  42. return;
  43. }
  44. $this->generateThumbnailsUrls($object);
  45. }
  46. }
  47. private function generateThumbnailsUrls(Photo $photo, ?Photo $logoPhoto = null): void
  48. {
  49. $thumbsUrls = [
  50. 'large' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'large'),
  51. 'small' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'small'),
  52. 'thumb' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'search-thumb'),
  53. 'logo' => $this->thumbURL->generateURL($this->uploaderHelper->asset($photo, 'file'), 'logo'),
  54. ];
  55. if ($logoPhoto) {
  56. $largeWithLogo = $this->thumbURL->generateURL($this->uploaderHelper->asset($logoPhoto, 'file'), 'slider-photo-watermarked-logo-large');
  57. $largeWithLogo .= '/'.ltrim((string) $this->uploaderHelper->asset($photo, 'file'), '/');
  58. $thumbsUrls['large'] = $largeWithLogo;
  59. }
  60. $photo->setThumbnails($thumbsUrls);
  61. }
  62. }