Completed
Push — master ( 6a0a65...c1d1d1 )
by Paweł
09:45
created

ImagesUploadListener::uploadImages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\CoreBundle\EventListener;
13
14
use Sylius\Component\Core\Model\ImagesAwareInterface;
15
use Sylius\Component\Core\Uploader\ImageUploaderInterface;
16
use Symfony\Component\EventDispatcher\GenericEvent;
17
use Webmozart\Assert\Assert;
18
19
/**
20
 * @author Grzegorz Sadowski <[email protected]>
21
 */
22
final class ImagesUploadListener
23
{
24
    /**
25
     * @var ImageUploaderInterface
26
     */
27
    private $uploader;
28
29
    /**
30
     * @param ImageUploaderInterface $uploader
31
     */
32
    public function __construct(ImageUploaderInterface $uploader)
33
    {
34
        $this->uploader = $uploader;
35
    }
36
37
    /**
38
     * @param GenericEvent $event
39
     */
40
    public function uploadImages(GenericEvent $event)
41
    {
42
        $subject = $event->getSubject();
43
        Assert::isInstanceOf($subject, ImagesAwareInterface::class);
44
45
        $this->uploadSubjectImages($subject);
46
    }
47
48
    /**
49
     * @param ImagesAwareInterface $subject
50
     */
51
    private function uploadSubjectImages(ImagesAwareInterface $subject)
52
    {
53
        $images = $subject->getImages();
54
        foreach ($images as $image) {
55
            if ($image->hasFile()) {
56
                $this->uploader->upload($image);
57
            }
58
59
            // Upload failed? Let's remove that image.
60
            if (null === $image->getPath()) {
61
                $images->removeElement($image);
62
            }
63
        }
64
    }
65
}
66