Completed
Pull Request — master (#41)
by
unknown
02:46
created

HandleMediaStorage   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 10
Bugs 0 Features 0
Metric Value
wmc 9
c 10
b 0
f 0
lcom 1
cbo 1
dl 0
loc 61
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 8 2
A handleMultiMedia() 0 13 3
A handleSingleMedia() 0 9 2
A getOrdersFrom() 0 12 2
1
<?php namespace Modules\Media\Events\Handlers;
2
3
use Modules\Media\Contracts\StoringMedia;
4
5
class HandleMediaStorage
6
{
7
    public function handle($event = null)
8
    {
9
        if ($event instanceof StoringMedia) {
10
            $this->handleMultiMedia($event);
11
12
            $this->handleSingleMedia($event);
13
        }
14
    }
15
16
    /**
17
     * Handle the request for the multi media partial
18
     * @param StoringMedia $event
19
     */
20
    private function handleMultiMedia(StoringMedia $event)
21
    {
22
        $entity = $event->getEntity();
23
        $postMedias = array_get($event->getSubmissionData(), 'medias_multi', []);
24
25
        foreach ($postMedias as $zone => $attributes) {
26
            $orders = $this->getOrdersFrom($attributes);
27
            foreach (array_get($attributes, 'files', []) as $fileId) {
28
                $order = array_search($fileId, $orders);
29
                $entity->files()->attach($fileId, ['imageable_type' => get_class($entity), 'zone' => $zone, 'order' => $order]);
30
            }
31
        }
32
    }
33
34
    /**
35
     * Handle the request to parse single media partials
36
     * @param StoringMedia $event
37
     */
38
    private function handleSingleMedia(StoringMedia $event)
39
    {
40
        $entity = $event->getEntity();
41
        $postMedia = array_get($event->getSubmissionData(), 'medias_single', []);
42
43
        foreach ($postMedia as $zone => $fileId) {
44
            $entity->files()->attach($fileId, ['imageable_type' => get_class($entity), 'zone' => $zone, 'order' => null]);
45
        }
46
    }
47
48
    /**
49
     * Parse the orders input and return an array of file ids, in order
50
     * @param array $attributes
51
     * @return array
52
     */
53
    private function getOrdersFrom(array $attributes)
54
    {
55
        $orderString = array_get($attributes, 'orders');
56
57
        if ($orderString === null) {
58
            return [];
59
        }
60
61
        $orders = explode(',', $orderString);
62
63
        return array_filter($orders);
64
    }
65
}
66