VendorsObserver   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 4
dl 0
loc 76
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A saved() 0 4 1
A creating() 0 4 1
A saveImage() 0 15 3
A getUnsetFields() 0 6 1
A removePreviousImage() 0 14 2
1
<?php
2
3
namespace App\Listeners\Observers;
4
use App\Services\ImageProcessor;
5
use Illuminate\Http\UploadedFile;
6
use Request;
7
use App\Image;
8
9
10
class VendorsObserver extends Observer
11
{
12
    /**
13
     * On model saved.
14
     *
15
     * @param $vendor
16
     */
17
18
    public function saved($vendor)
19
    {
20
        $this->saveImage($vendor);
21
    }
22
23
    /**
24
     * On model creating.
25
     *
26
     * @param $vendor
27
     */
28
    public function creating($vendor)
29
    {
30
        $this->unsetNoneModelFields($vendor, $this->getUnsetFields());
31
    }
32
33
    /**
34
     * @param $vendor
35
     * @throws \Exception
36
     */
37
    public function saveImage($vendor)
38
    {
39
        $image = Request::file('image');
40
41
        if($image) {
42
            if ($image instanceof UploadedFile) {
43
                $this->removePreviousImage($vendor);
44
                $location = 'upload/vendors/'.$vendor->id;
45
                $processor = new ImageProcessor();
46
                $processor->uploadAndCreate($image, $vendor, null, $location);
47
            } else {
48
                throw new \Exception('Invalid Image');
49
            }
50
        }
51
    }
52
53
    /**
54
     * Fields for unset.
55
     *
56
     * @return array
57
     */
58
    public function getUnsetFields()
59
    {
60
        return [
61
            'image'
62
        ];
63
    }
64
65
    /**
66
     * Remove images.
67
     *
68
     * @param $vendor
69
     * @return void
70
     */
71
    private function removePreviousImage($vendor)
72
    {
73
        $images = $vendor->images; // Incoming array of images
74
        //, but for categories can exists only one image
75
76
        if(count($images))
77
            $images->each(function(Image $image){
78
                $image->delete();
79
                // remove image.
80
                // @events: deleted(); remove file
81
            });
82
83
84
    }
85
}