Completed
Pull Request — master (#139)
by Sebastian
10:07
created

ContentBlock::updateWithAttributes()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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