Resource::setFileAttribute()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Backpack\CRUD\app\Models\Traits\CrudTrait;
7
use Backpack\CRUD\app\Models\Traits\SpatieTranslatable\HasTranslations;
8
use Illuminate\Support\Facades\Storage;
9
10
/**
11
 * Class Resource
12
 *
13
 * @property int id
14
 * @property string name
15
 * @property string file
16
 */
17
18
class Resource extends Model
19
{
20
    use CrudTrait;
21
    use HasTranslations;
22
23
    /**
24
     * Delete file in resources folder
25
     *
26
     */
27
    public static function boot(): void
28
    {
29
        parent::boot();
30
        static::deleting(function ($obj): void {
31
            Storage::disk('public')->delete($obj->file);
32
        });
33
    }
34
35
    /**
36
     * The model's attributes that admin cannot change.
37
     *
38
     * @var array
39
     */
40
    protected $guarded = ['id'];
41
42
    /**
43
     * The model's attributes that are mass assignable.
44
     *
45
     * @var array
46
     */
47
    protected $fillable = ['name', 'file'];
48
49
    /**
50
     * The model's attributes that are translated.
51
     *
52
     * @var array
53
     */
54
    protected $translatable = ['name'];
55
56
    /**
57
     * Set the value of file name attribute in DB and upload file to disk.
58
     *
59
     * @param string $value Incoming value for 'file' attribute.
60
     */
61
    public function setFileAttribute(string $value): void
62
    {
63
        $request = \Request::instance();
64
65
        // Check if a new file has been uploaded if not then save value to file attribute
66
        if ($request->hasFile('file')) {
67
            $this->uploadFileToDisk($value, 'file', 'public', 'resources');
68
        } else {
69
            $this->attributes['file'] = $value;
0 ignored issues
show
Bug Best Practice introduced by
The property attributes does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
        }
71
    }
72
}
73