|
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
|
29 |
|
public function __construct(array $params) |
|
24
|
|
|
{ |
|
25
|
29 |
|
$this->params = $params; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @psalm-suppress PossiblyNullReference |
|
30
|
|
|
* @param Ruleable&Element $element |
|
31
|
|
|
* @return bool |
|
32
|
|
|
*/ |
|
33
|
3 |
|
public function validate(Ruleable $element): bool |
|
34
|
|
|
{ |
|
35
|
|
|
/** @var UploadedFileInterface|false $value */ |
|
36
|
3 |
|
$value = \getValueByIndexPath($element->getName(), $this->getRequest()->getFilesData()->toArray()); |
|
|
|
|
|
|
37
|
|
|
|
|
38
|
3 |
|
if (false === $this->check($value, $element)) { |
|
39
|
1 |
|
return false; |
|
40
|
|
|
} |
|
41
|
2 |
|
return true; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
17 |
|
private function check(UploadedFileInterface|false $value, Ruleable $element): bool |
|
45
|
|
|
{ |
|
46
|
|
|
/** @var array|scalar $options */ |
|
47
|
17 |
|
foreach ($this->params as $rule => $options) { |
|
48
|
16 |
|
if (is_int($rule) && is_string($options)) { |
|
49
|
10 |
|
$rule = $options; |
|
50
|
10 |
|
$options = []; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
|
|
54
|
|
|
/** @var string $rule */ |
|
55
|
16 |
|
$className = sprintf('\Enjoys\Forms\Rule\UploadCheck\%sCheck', ucfirst($rule)); |
|
56
|
|
|
|
|
57
|
|
|
/** @var class-string<UploadCheckInterface> $className */ |
|
58
|
16 |
|
Assert::classExists($className, sprintf('Unknown Check Upload: [%s]', $className)); |
|
59
|
|
|
|
|
60
|
15 |
|
if ((new $className($value, $element, ...(array)$options))->check() === false) { |
|
61
|
6 |
|
return false; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
10 |
|
return true; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|