SeoTranslationImagesUploadListener   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 26
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A uploadMedia() 0 16 5
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