1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Enjoys\Forms\Rule; |
||
6 | |||
7 | use Enjoys\Forms\Element; |
||
8 | use Enjoys\Forms\Interfaces\Ruleable; |
||
9 | use Enjoys\Forms\Rule\UploadCheck\UploadCheckInterface; |
||
10 | use Enjoys\Forms\Traits\Request; |
||
11 | use Psr\Http\Message\UploadedFileInterface; |
||
12 | use Webmozart\Assert\Assert; |
||
13 | |||
14 | class Upload implements RuleInterface |
||
15 | { |
||
16 | use Request; |
||
17 | |||
18 | public const REQUIRED = 'required'; |
||
19 | public const EXTENSIONS = 'extensions'; |
||
20 | |||
21 | private array $params; |
||
22 | |||
23 | 31 | public function __construct(array $params) |
|
24 | { |
||
25 | 31 | $this->params = $params; |
|
26 | } |
||
27 | |||
28 | /** |
||
29 | * @psalm-suppress MixedArgument |
||
30 | * @param Ruleable&Element $element |
||
31 | * @return bool |
||
32 | */ |
||
33 | 5 | public function validate(Ruleable $element): bool |
|
34 | { |
||
35 | /** @var UploadedFileInterface[] $uploadedFiles */ |
||
36 | 5 | $uploadedFiles = $this->getUploadedFiles( |
|
37 | 5 | \getValueByIndexPath($element->getName(), $this->getRequest()->getUploadedFiles()) |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
38 | 5 | ); |
|
39 | |||
40 | 5 | foreach ($uploadedFiles as $uploadedFile) { |
|
41 | 5 | if (false === $this->check($uploadedFile, $element)) { |
|
42 | 2 | return false; |
|
43 | } |
||
44 | } |
||
45 | 3 | return true; |
|
46 | } |
||
47 | |||
48 | 19 | private function check(UploadedFileInterface|false $value, Ruleable $element): bool |
|
49 | { |
||
50 | /** @var array|scalar $options */ |
||
51 | 19 | foreach ($this->params as $rule => $options) { |
|
52 | 18 | if (is_int($rule) && is_string($options)) { |
|
53 | 12 | $rule = $options; |
|
54 | 12 | $options = []; |
|
55 | } |
||
56 | |||
57 | |||
58 | /** @var string $rule */ |
||
59 | 18 | $className = sprintf('\Enjoys\Forms\Rule\UploadCheck\%sCheck', ucfirst($rule)); |
|
60 | |||
61 | /** @var class-string<UploadCheckInterface> $className */ |
||
62 | 18 | Assert::classExists($className, sprintf('Unknown Check Upload: [%s]', $className)); |
|
63 | |||
64 | 17 | if ((new $className($value, $element, ...(array)$options))->check() === false) { |
|
65 | 7 | return false; |
|
66 | } |
||
67 | } |
||
68 | 11 | return true; |
|
69 | } |
||
70 | |||
71 | /** |
||
72 | * @param false|UploadedFileInterface[]|UploadedFileInterface $item |
||
73 | * @return array |
||
74 | * @noinspection PhpMissingParamTypeInspection |
||
75 | */ |
||
76 | 5 | private function getUploadedFiles($item): array |
|
77 | { |
||
78 | 5 | if (is_array($item)) { |
|
79 | 1 | return $item; |
|
80 | } |
||
81 | 4 | return [$item]; |
|
82 | } |
||
83 | } |
||
84 |