Completed
Pull Request — master (#139)
by Sebastian
03:06
created

ContentBlock::setOrder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Arr;
7
use Spatie\Translatable\HasTranslations;
8
use Spatie\Blender\Model\Traits\HasMedia;
9
use Spatie\Blender\Model\Traits\Draftable;
10
use Spatie\EloquentSortable\SortableTrait;
11
use Illuminate\Database\Eloquent\Relations\MorphTo;
12
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
13
14
class ContentBlock extends Model implements HasMediaConversions
15
{
16
    use Draftable, SortableTrait, HasTranslations, HasMedia;
17
18
    public $translatable = ['name', 'text'];
19
    protected $guarded = [];
20
21
    public function subject(): MorphTo
22
    {
23
        return $this->morphTo('model');
24
    }
25
26
    public function registerMediaConversions()
27
    {
28
        $this->addMediaConversion('admin')
29
            ->setWidth(368)
30
            ->setHeight(232)
31
            ->nonQueued();
32
33
        $this->addMediaConversion('thumb')
34
            ->setWidth(368)
35
            ->setHeight(232)
36
            ->performOnCollections('images');
37
    }
38
39
    public function mediaLibraryCollectionNames(): array
40
    {
41
        return array_keys($this->subject->getContentBlockMediaLibraryCollections());
42
    }
43
44
    public function mediaLibraryCollectionType(string $name): string
45
    {
46
        return $this->subject->getContentBlockMediaLibraryCollections()[$name];
47
    }
48
49
    public function updateWithAttributes(array $values)
50
    {
51
        $this->draft = false;
52
        $this->type = $values['type'];
53
54
        foreach ($this->translatable as $attribute) {
55
            $this->setTranslations($attribute, $values[$attribute] ?? []);
56
        }
57
58
        foreach ($this->mediaLibraryCollectionNames() as $collection) {
59
            if (! isset($values[$collection])) {
60
                continue;
61
            }
62
63
            $media = array_filter($values[$collection], function ($media) {
64
                return ($media['markedForRemoval'] ?? false) !== true;
65
            });
66
67
            $updatedMedia = $this->updateMedia($media, $collection);
68
69
            $this->media()
70
                ->whereCollectionName($collection)
71
                ->whereNotIn('id', Arr::pluck($updatedMedia, 'id'))
72
                ->delete();
73
        }
74
75
        $this->save();
76
77
        return $this;
78
    }
79
80
    public function setOrder(int $i)
81
    {
82
        $this->order_column = $i;
83
84
        $this->save();
85
86
        return $this;
87
    }
88
}
89