Completed
Push — master ( 652977...26682b )
by Nicolas
03:01
created

HandleMediaStorage::getZoneFrom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php namespace Modules\Media\Events\Handlers;
2
3
use Modules\Media\Contracts\StoringMedia;
4
use Modules\Media\Image\Imagy;
5
use Modules\Media\Repositories\FileRepository;
6
use Modules\Media\Services\FileService;
7
8
class HandleMediaStorage
9
{
10
    /**
11
     * @var FileService
12
     */
13
    private $fileService;
14
    /**
15
     * @var FileRepository
16
     */
17
    private $file;
18
    /**
19
     * @var Imagy
20
     */
21
    private $imagy;
22
23
    public function __construct(FileService $fileService, FileRepository $file, Imagy $imagy)
24
    {
25
        $this->fileService = $fileService;
26
        $this->file = $file;
27
        $this->imagy = $imagy;
28
    }
29
30
    public function handle(StoringMedia $event)
31
    {
32
        $this->handleMultiMedia($event);
33
34
        $this->handleSingleMedia($event);
35
    }
36
37
    /**
38
     * Handle the request for the multi media partial
39
     * @param StoringMedia $event
40
     */
41
    private function handleMultiMedia(StoringMedia $event)
42
    {
43
        $entity = $event->getEntity();
44
        $postMedias = array_get($event->getSubmissionData(), 'medias_multi', []);
45
46
        foreach ($postMedias as $zone => $attributes) {
47
            $orders = $this->getOrdersFrom($attributes);
48
            foreach ($attributes['files'] as $fileId) {
49
                $order = array_search($fileId, $orders);
50
                $entity->files()->attach($fileId, ['imageable_type' => get_class($entity), 'zone' => $zone, 'order' => $order]);
51
            }
52
        }
53
    }
54
55
    /**
56
     * Handle the request to parse single media partials
57
     * @param StoringMedia $event
58
     */
59
    private function handleSingleMedia(StoringMedia $event)
60
    {
61
        $entity = $event->getEntity();
62
        $postMedia = array_get($event->getSubmissionData(), 'medias_single', []);
63
64
        foreach ($postMedia as $zone => $fileId) {
65
            $entity->files()->attach($fileId, ['imageable_type' => get_class($entity), 'zone' => $zone, 'order' => null]);
66
        }
67
    }
68
69
    /**
70
     * Parse the orders input and return an array of file ids, in order
71
     * @param array $attributes
72
     * @return array
73
     */
74
    private function getOrdersFrom(array $attributes)
75
    {
76
        $orderString = array_get($attributes, 'orders');
77
78
        if ($orderString === null) {
79
            return [];
80
        }
81
82
        $orders = explode(',', $orderString);
83
84
        return array_filter($orders);
85
    }
86
}
87