1 | <?php |
||||
2 | |||||
3 | declare(strict_types=1); |
||||
4 | |||||
5 | |||||
6 | namespace Enjoys\Upload\Rule; |
||||
7 | |||||
8 | |||||
9 | use Enjoys\Upload\Exception\RuleException; |
||||
10 | use Enjoys\Upload\RuleInterface; |
||||
11 | use Psr\Http\Message\UploadedFileInterface; |
||||
12 | |||||
13 | use function array_map; |
||||
14 | use function explode; |
||||
15 | use function pathinfo; |
||||
16 | use function sprintf; |
||||
17 | use function strtolower; |
||||
18 | |||||
19 | final class Extension implements RuleInterface |
||||
20 | { |
||||
21 | private string $errorMessage; |
||||
22 | private array $allowed = []; |
||||
23 | |||||
24 | 5 | public function __construct(string $errorMessage = null) |
|||
25 | { |
||||
26 | 5 | $this->errorMessage = $errorMessage ?? 'Files with the %s extension are not allowed'; |
|||
27 | } |
||||
28 | |||||
29 | |||||
30 | /** |
||||
31 | * @param string|string[] $extension |
||||
32 | * @return $this |
||||
33 | */ |
||||
34 | 5 | public function allow(array|string $extension): Extension |
|||
35 | { |
||||
36 | 5 | if (is_string($extension)){ |
|||
0 ignored issues
–
show
introduced
by
![]() |
|||||
37 | 4 | $extension = explode(",", $extension); |
|||
38 | } |
||||
39 | |||||
40 | 5 | $this->allowed = array_map('trim', array_map('strtolower', $extension)); |
|||
41 | |||||
42 | 5 | return $this; |
|||
43 | } |
||||
44 | |||||
45 | 5 | public function check(UploadedFileInterface $file): void |
|||
46 | { |
||||
47 | 5 | $extension = strtolower(pathinfo( |
|||
0 ignored issues
–
show
It seems like
pathinfo($file->getClien...ule\PATHINFO_EXTENSION) can also be of type array ; however, parameter $string of strtolower() 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
![]() |
|||||
48 | 5 | $file->getClientFilename() ?? '', |
|||
49 | 5 | PATHINFO_EXTENSION |
|||
50 | 5 | )); |
|||
51 | |||||
52 | 5 | if (!in_array($extension, $this->allowed, true)){ |
|||
53 | 3 | throw new RuleException(sprintf($this->errorMessage, $extension)); |
|||
54 | } |
||||
55 | } |
||||
56 | } |
||||
57 |