Skip to content

Commit 8d4fe5b

Browse files
Merge branch 'use_custom_properties_in_media' into ozu-file-download-support
2 parents 846928e + bdab08c commit 8d4fe5b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/Eloquent/Media.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,18 @@
88
use Illuminate\Database\Eloquent\Factories\HasFactory;
99
use Illuminate\Database\Eloquent\Model;
1010
use Illuminate\Database\Eloquent\Relations\MorphTo;
11+
use Illuminate\Support\Facades\Schema;
1112

1213
class Media extends Model
1314
{
1415
use HasFactory;
1516

1617
protected $guarded = [];
1718
protected $table = 'medias';
19+
protected $casts = [
20+
'custom_properties' => 'array',
21+
'size' => 'integer',
22+
];
1823

1924
protected static function newFactory()
2025
{
@@ -56,4 +61,45 @@ public function humanReadableSize($precision = 2): ?string
5661
return $this->size;
5762
}
5863
}
64+
65+
/**
66+
* @param string $key
67+
* @return mixed|null
68+
*/
69+
public function getAttribute($key)
70+
{
71+
if (! $this->isRealAttribute($key)) {
72+
return $this->getAttribute('custom_properties')[$key] ?? null;
73+
}
74+
75+
return parent::getAttribute($key);
76+
}
77+
78+
/**
79+
* @param string $key
80+
* @param mixed $value
81+
* @return Model
82+
*/
83+
public function setAttribute($key, $value)
84+
{
85+
if (! $this->isRealAttribute($key)) {
86+
return $this->updateCustomProperty($key, $value);
87+
}
88+
89+
return parent::setAttribute($key, $value);
90+
}
91+
92+
protected function updateCustomProperty(string $key, $value): self
93+
{
94+
$properties = $this->getAttribute('custom_properties');
95+
$properties[$key] = $value;
96+
$this->setAttribute('custom_properties', $properties);
97+
98+
return $this;
99+
}
100+
101+
protected function isRealAttribute(string $name): bool
102+
{
103+
return Schema::hasColumn($this->getTable(), $name) ?? false;
104+
}
59105
}

0 commit comments

Comments
 (0)