LaruploadObservers::boot()   B
last analyzed

Complexity

Conditions 8
Paths 1

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 16
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 31
rs 8.4444
1
<?php
2
3
namespace Mostafaznv\Larupload\Concerns;
4
5
6
use Illuminate\Database\Eloquent\SoftDeletingScope;
7
8
trait LaruploadObservers
9
{
10
    protected static function boot(): void
11
    {
12
        parent::boot();
13
14
        static::saved(function($model) {
15
            $shouldSave = false;
16
17
            foreach ($model->attachments as $attachment) {
18
                if (!$attachment->isUploaded()) {
19
                    $shouldSave = true;
20
21
                    $model = $attachment->saved($model);
22
                }
23
            }
24
25
            if ($shouldSave) {
26
                $model->save();
27
            }
28
        });
29
30
        static::deleted(function($model) {
31
            if (!$model->hasGlobalScope(SoftDeletingScope::class) or $model->isForceDeleting()) {
32
                foreach ($model->attachments as $attachment) {
33
                    $attachment->deleted();
34
                }
35
            }
36
        });
37
38
        static::retrieved(function($model) {
39
            foreach ($model->attachments as $attachment) {
40
                $attachment->setOutput($model);
41
            }
42
        });
43
    }
44
}
45