-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedia.php
106 lines (86 loc) · 2.58 KB
/
Media.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Code16\OzuClient\Eloquent;
use Code16\OzuClient\Database\Factories\MediaFactory;
use Code16\OzuClient\Support\Thumbnails\Thumbnail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\Schema;
class Media extends Model
{
use HasFactory;
protected $guarded = [];
protected $table = 'medias';
protected $casts = [
'custom_properties' => 'array',
'size' => 'integer',
];
protected static function newFactory()
{
return new MediaFactory;
}
public function model(): MorphTo
{
return $this->morphTo('model');
}
public function thumbnail(?int $width = null, ?int $height = null, bool $fit = false): ?string
{
return app(Thumbnail::class)
->forMedia($this)
->make($width, $height, $fit);
}
public function download(): ?string
{
return app(Thumbnail::class)
->forMedia($this)
->download();
}
public function humanReadableSize($precision = 2): ?string
{
if ($this->size < 0) {
return null;
}
if ($this->size >= 0) {
$size = (int) $this->size;
$base = log($size) / log(1024);
$suffixes = [' bytes', ' KB', ' MB', ' GB', ' TB'];
return $this->size === 0 ? '0 bytes' : (round(pow(1024, $base - floor($base)), $precision).$suffixes[floor($base)]);
} else {
return $this->size;
}
}
/**
* @param string $key
* @return mixed|null
*/
public function getAttribute($key)
{
if (! $this->isRealAttribute($key)) {
return $this->getAttribute('custom_properties')[$key] ?? null;
}
return parent::getAttribute($key);
}
/**
* @param string $key
* @param mixed $value
* @return Model
*/
public function setAttribute($key, $value)
{
if (! $this->isRealAttribute($key)) {
return $this->updateCustomProperty($key, $value);
}
return parent::setAttribute($key, $value);
}
protected function updateCustomProperty(string $key, $value): self
{
$properties = $this->getAttribute('custom_properties');
$properties[$key] = $value;
$this->setAttribute('custom_properties', $properties);
return $this;
}
protected function isRealAttribute(string $name): bool
{
return Schema::hasColumn($this->getTable(), $name) ?? false;
}
}