Passed
Push — main ( 31c909...3a0b15 )
by Yaroslav
03:28
created

ExportStoredFile::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 5
dl 0
loc 13
ccs 0
cts 9
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace NovaExportConfiguration\Models;
4
5
use Illuminate\Database\Eloquent\Casts\Attribute;
6
use Illuminate\Database\Eloquent\Factories\HasFactory;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Facades\Storage;
9
use JsonFieldCast\Casts\SimpleJsonField;
10
use NovaExportConfiguration\Database\Factories\ExportStoredFileFactory;
11
12
/**
13
 * @property string $type
14
 * @property string $disk
15
 * @property string $path
16
 * @property string $name
17
 * @property \JsonFieldCast\Json\SimpleJsonField $meta
18
 * @property-read string $download_link
19
 */
20
class ExportStoredFile extends Model
21
{
22
    use HasFactory;
23
24
    protected $guarded = [];
25
26
    public $withoutActionEvents = true;
27
28
    protected $casts = [
29
        'meta' => SimpleJsonField::class,
30
    ];
31
32
    public function getTable(): string
33
    {
34
        return config('nova-export-configuration.tables.export_config_stored_files');
35
    }
36
37
    protected static function boot(): void
38
    {
39
        parent::boot();
40
41
        self::deleting(function (self $model) {
42
            $storage = Storage::disk($model->disk);
43
            if ($storage->exists($model->path)) {
44
                $storage->delete($model->path);
45
            }
46
        });
47
    }
48
49
    public static function init(string $type, string $disk, string $path, string $name, ?\Closure $tap = null): static
50
    {
51
        $model       = new static();
52
        $model->type = $type;
53
        $model->disk = $disk;
54
        $model->path = $path;
55
        $model->name = $name;
56
57
        if(is_callable($tap)) {
58
            $tap($model);
59
        }
60
61
        return $model;
62
    }
63
64
    public function downloadLink(): Attribute
65
    {
66
        return Attribute::get(fn () => route(config('nova-export-configuration.defaults.download_route'), $this->path));
67
    }
68
69
    protected static function newFactory(): ExportStoredFileFactory
70
    {
71
        return ExportStoredFileFactory::new();
72
    }
73
}
74