src/Sylius/Bundle/CoreBundle/EventListener/ImagesUploadListener.php line 31

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\CoreBundle\EventListener;
  12. use Sylius\Component\Core\Model\ImagesAwareInterface;
  13. use Sylius\Component\Core\Uploader\ImageUploaderInterface;
  14. use Symfony\Component\EventDispatcher\GenericEvent;
  15. use Webmozart\Assert\Assert;
  16. final class ImagesUploadListener
  17. {
  18.     /** @var ImageUploaderInterface */
  19.     private $uploader;
  20.     public function __construct(ImageUploaderInterface $uploader)
  21.     {
  22.         $this->uploader $uploader;
  23.     }
  24.     public function uploadImages(GenericEvent $event): void
  25.     {
  26.         $subject $event->getSubject();
  27.         Assert::isInstanceOf($subjectImagesAwareInterface::class);
  28.         $this->uploadSubjectImages($subject);
  29.     }
  30.     private function uploadSubjectImages(ImagesAwareInterface $subject): void
  31.     {
  32.         $images $subject->getImages();
  33.         foreach ($images as $image) {
  34.             if ($image->hasFile()) {
  35.                 $this->uploader->upload($image);
  36.             }
  37.             // Upload failed? Let's remove that image.
  38.             if (null === $image->getPath()) {
  39.                 $images->removeElement($image);
  40.             }
  41.         }
  42.     }
  43. }