SeoTranslationImagesUploadListener::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace JoppeDc\SyliusBetterSeoPlugin\EventListener;
6
7
use JoppeDc\SyliusBetterSeoPlugin\Entity\HasSeoInterface;
8
use JoppeDc\SyliusBetterSeoPlugin\Entity\SeoImageInterface;
9
use JoppeDc\SyliusBetterSeoPlugin\Entity\SeoInterface;
10
use JoppeDc\SyliusBetterSeoPlugin\Entity\SeoTranslationInterface;
11
use Sylius\Component\Core\Uploader\ImageUploaderInterface;
12
use Symfony\Component\EventDispatcher\GenericEvent;
13
use Webmozart\Assert\Assert;
14
15
class SeoTranslationImagesUploadListener
16
{
17
    /** @var ImageUploaderInterface */
18
    private $uploader;
19
20
    public function __construct(ImageUploaderInterface $uploader)
21
    {
22
        $this->uploader = $uploader;
23
    }
24
25
    public function uploadMedia(GenericEvent $event): void
26
    {
27
        $subject = $event->getSubject();
28
        Assert::isInstanceOf($subject, HasSeoInterface::class);
29
        $seo = $subject->getSeo();
30
        Assert::isInstanceOf($seo, SeoInterface::class);
31
        /** @var SeoTranslationInterface $translation */
32
        foreach ($seo->getTranslations() as $translation) {
33
            $image = $translation->getImage();
34
            if ($image instanceof SeoImageInterface) {
35
                if ($image->hasFile()) {
36
                    $this->uploader->upload($image);
37
                }
38
                // Upload failed? Let's remove that image.
39
                if (null === $image->getPath()) {
40
                    $translation->setImage(null);
41
                }
42
            }
43
        }
44
    }
45
}
46