Skip to content

Commit

Permalink
Merge pull request #264 from moonshine-software/file-custom-names
Browse files Browse the repository at this point in the history
feat(fields): File custom name
  • Loading branch information
lee-to authored May 14, 2023
2 parents 6a0dde2 + 3a81dbb commit a660848
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Traits/Fields/FileTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MoonShine\Traits\Fields;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
Expand All @@ -23,6 +24,8 @@ trait FileTrait

protected bool $keepOriginalFileName = false;

protected ?Closure $customName = null;

/**
* @deprecated Will be removed
*/
Expand All @@ -35,6 +38,13 @@ public function keepOriginalFileName(): static
return $this;
}

public function customName(Closure $name): static
{
$this->customName = $name;

return $this;
}

public function allowedExtensions(array $allowedExtensions): static
{
$this->allowedExtensions = $allowedExtensions;
Expand Down Expand Up @@ -106,6 +116,14 @@ public function store(UploadedFile $file): string
);
}

if (is_callable($this->customName)) {
return $file->storeAs(
$this->getDir(),
call_user_func($this->customName, $file),
$this->getDisk()
);
}

return $file->store($this->getDir(), $this->getDisk());
}

Expand Down
19 changes: 19 additions & 0 deletions tests/Feature/Fields/FileFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,22 @@

Storage::disk('public')->assertExists('files/'.$avatar->hashName());
});

it('custom name', function () {
$avatar = UploadedFile::fake()->image('avatar.png');

fakeRequest(method: 'POST', parameters: [
'avatar' => $avatar,
]);

$this->field
->customName(function (UploadedFile $file) {
return 'testing.' . $file->extension();
})
->save($this->item);

expect($this->item->avatar)
->toBe('files/testing.png');

Storage::disk('public')->assertExists('files/testing.png');
});

0 comments on commit a660848

Please sign in to comment.