mostafaznv /
larupload
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Mostafaznv\Larupload\Actions; |
||
| 4 | |||
| 5 | use Illuminate\Http\UploadedFile; |
||
| 6 | use Illuminate\Support\Carbon; |
||
| 7 | use Mostafaznv\Larupload\Enums\LaruploadNamingMethod; |
||
| 8 | use Mostafaznv\Larupload\Helpers\Slug; |
||
| 9 | |||
| 10 | class SetFileNameAction |
||
| 11 | { |
||
| 12 | public function __construct( |
||
| 13 | private readonly UploadedFile $file, |
||
| 14 | private readonly LaruploadNamingMethod $namingMethod, |
||
| 15 | private readonly ?string $lang = null |
||
| 16 | ) {} |
||
| 17 | |||
| 18 | public static function make(UploadedFile $file, LaruploadNamingMethod $namingMethod, ?string $lang = null): static |
||
| 19 | { |
||
| 20 | return new static($file, $namingMethod, $lang); |
||
| 21 | } |
||
| 22 | |||
| 23 | |||
| 24 | public function generate(): string |
||
| 25 | { |
||
| 26 | $format = $this->file->getClientOriginalExtension(); |
||
| 27 | |||
| 28 | $name = match ($this->namingMethod) { |
||
| 29 | LaruploadNamingMethod::HASH_FILE => $this->generateHashFile(), |
||
| 30 | LaruploadNamingMethod::TIME => Carbon::now()->unix(), |
||
| 31 | default => $this->generateSlugFromFile(), |
||
| 32 | }; |
||
| 33 | |||
| 34 | return "$name.$format"; |
||
| 35 | } |
||
| 36 | |||
| 37 | private function generateHashFile(): string |
||
| 38 | { |
||
| 39 | return hash_file('md5', $this->file->getRealPath()); |
||
| 40 | } |
||
| 41 | |||
| 42 | private function generateSlugFromFile(): string |
||
| 43 | { |
||
| 44 | $name = $this->file->getClientOriginalName(); |
||
| 45 | $name = pathinfo($name, PATHINFO_FILENAME); |
||
| 46 | $num = rand(0, 9999); |
||
| 47 | |||
| 48 | $slug = Slug::make($this->lang)->generate($name); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 49 | |||
| 50 | return "$slug-$num"; |
||
| 51 | } |
||
| 52 | } |
||
| 53 |