*/ protected $casts = [ 'id' => 'integer', 'file_key' => 'string', 'file_size' => 'int', 'file_mimetype' => 'string', 'file_metadata' => '?json-array', 'type' => 'string', 'description' => '?string', 'language_code' => '?string', 'uploaded_by' => 'integer', 'updated_by' => 'integer', ]; /** * @param array|null $data */ public function __construct(array $data = null) { parent::__construct($data); $this->initFileProperties(); } public function initFileProperties(): void { if ($this->file_key !== '') { [ 'filename' => $filename, 'dirname' => $dirname, 'extension' => $extension, ] = pathinfo($this->file_key); $this->attributes['file_url'] = service('file_manager')->getUrl($this->file_key); $this->attributes['file_name'] = $filename; $this->attributes['file_directory'] = $dirname; $this->attributes['file_extension'] = $extension; } } public function setFile(File $file): self { $this->attributes['type'] = $this->type; $this->attributes['file_mimetype'] = $file->getMimeType(); $this->attributes['file_metadata'] = json_encode(lstat((string) $file), JSON_INVALID_UTF8_IGNORE); if ($filesize = $file->getSize()) { $this->attributes['file_size'] = $filesize; } $this->attributes['file'] = $file; return $this; } public function saveFile(): bool { if (! $this->attributes['file'] || ! $this->file_key) { return false; } $this->attributes['file_key'] = service('file_manager')->save($this->attributes['file'], $this->file_key); return true; } public function deleteFile(): bool { return service('file_manager')->delete($this->file_key); } public function rename(): bool { $newFileKey = $this->file_directory . '/' . (new File(''))->getRandomName() . '.' . $this->file_extension; $db = db_connect(); $db->transStart(); if (! (new MediaModel())->update($this->id, [ 'file_key' => $newFileKey, ])) { return false; } if (! service('file_manager')->rename($this->file_key, $newFileKey)) { $db->transRollback(); return false; } $db->transComplete(); return true; } }