[ '' => 0, '外包装图片' => 1, '内物破碎图片' => 2, '交易截图' => 3, '退款成功截图' => 4, ], 'tag' => [ '创建' => 0, '完成' => 1, '标记' => 2, ], ]; function __construct(array $attributes = []) { foreach (self::$enums as &$enum) { $enum = $enum + array_flip($enum); } parent::__construct($attributes); } public function getTypeAttribute($value) { if (!$value) return ''; return self::$enums['type'][$value]; } public function setTypeAttribute($value) { if (!$value) return ; if (is_numeric($value)) { $this->attributes['type'] = $value; } else { $this->attributes['type'] = self::$enums['type'][$value]; } } public function getTagAttribute($value) { if($value == 0) return self::$enums['tag'][$value]; if (!$value) return ''; return self::$enums['tag'][$value]; } public function setTagAttribute($value) { if (!$value) return; if (is_numeric($value)) { $this->attributes['tag'] = $value; } else { $this->attributes['tag'] = self::$enums['tag'][$value]; } } public function workOrder(): BelongsTo { return $this->belongsTo(WorkOrder::class); } public function uploadFile(): HasOne { return $this->hasOne(UploadFile::class,'table_id','id')->where('table_name',$this->getTable()); } public function saveFile(UploadedFile $image): bool { if (!$this->checkFile($image)) return false; $tmpFile = $image->getRealPath(); $fileSuffix = $image->getClientOriginalExtension(); $dirPath = $this->getStorageDirPath(); $fileName = date('ymd') . '-' . Uuid::uuid1(); $pathName = $dirPath . $fileName .'.' . $fileSuffix; $result = move_uploaded_file($tmpFile, $pathName); if(!$result) return false; $this->uploadFile()->create( [ 'url' => '/files/workOrder/'.$fileName, 'type' => $fileSuffix,'table_name'=>$this->getTable()] ); return true; } public function checkFile($image): bool { $tmpFile = $image->getRealPath(); $fileSuffix = $image->getClientOriginalExtension(); if (!is_uploaded_file($tmpFile)) return false; // if ($image->getSize() > 5 * 1024 * 1024) return false; if (!in_array($fileSuffix,[ 'gif','image','jpeg','jpg','png','svg'])) return false; return true; } public function getStorageDirPath(): string { $path = ['app','public','files','workOrder']; $path = join(DIRECTORY_SEPARATOR,$path); $dirPath = storage_path($path); if (!file_exists($dirPath)) { mkdir($dirPath); } return $dirPath.DIRECTORY_SEPARATOR; } public function updateFile($image) { $this->deleteStorageFile(); $this->uploadFile()->delete(); $this->saveFile($image); } public function deleteStorageFile() { $path = $this->getPathName(); if (!$path) return; if (file_exists($path)){ unlink($path); } } public function getPathName(): ?string { if (!$this->uploadFile) return null; $names = []; preg_match("/([\w]+)$/", $this->uploadFile->url,$names); $path = ['app','public','files','workOrder' , $names[0],".{$this->uploadFile->type}"]; $path = join(DIRECTORY_SEPARATOR,$path); return storage_path($path); } }