SetFileNameAction   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 41
rs 10
wmc 5

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A generate() 0 11 1
A generateSlugFromFile() 0 9 1
A make() 0 3 1
A generateHashFile() 0 3 1
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
It seems like $name can also be of type array; however, parameter $string of Mostafaznv\Larupload\Helpers\Slug::generate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

48
        $slug = Slug::make($this->lang)->generate(/** @scrutinizer ignore-type */ $name);
Loading history...
49
50
        return "$slug-$num";
51
    }
52
}
53