|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
namespace Enjoys\Forms\Rule\UploadCheck; |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
use Enjoys\Forms\Interfaces\Ruleable; |
|
10
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
|
11
|
|
|
use Webmozart\Assert\Assert; |
|
12
|
|
|
|
|
13
|
|
|
final class ExtensionsCheck implements UploadCheckInterface |
|
14
|
|
|
{ |
|
15
|
|
|
|
|
16
|
|
|
|
|
17
|
|
|
private UploadedFileInterface|false $value; |
|
18
|
|
|
private Ruleable $element; |
|
19
|
|
|
private array|string $options; |
|
20
|
|
|
|
|
21
|
4 |
|
public function __construct(false|UploadedFileInterface $value, Ruleable $element, array|string $options) |
|
22
|
|
|
{ |
|
23
|
4 |
|
$this->value = $value; |
|
24
|
4 |
|
$this->element = $element; |
|
25
|
4 |
|
$this->options = $options; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
4 |
|
public function check(): bool |
|
29
|
|
|
{ |
|
30
|
4 |
|
if ($this->value === false) { |
|
31
|
1 |
|
return true; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
3 |
|
$parsed = $this->parseOptions($this->options); |
|
35
|
|
|
|
|
36
|
3 |
|
Assert::string( $parsed['param']); |
|
37
|
3 |
|
$expected_extensions = \array_map('trim', \explode(",", $parsed['param'])); |
|
38
|
|
|
|
|
39
|
3 |
|
$message = $parsed['message']; |
|
40
|
|
|
|
|
41
|
3 |
|
$extension = pathinfo($this->value->getClientFilename() ?? '', PATHINFO_EXTENSION); |
|
42
|
|
|
|
|
43
|
3 |
|
if (is_null($message)) { |
|
44
|
1 |
|
$message = 'Загрузка файлов с расширением .' . $extension . ' запрещена'; |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
|
|
48
|
3 |
|
if (!in_array($extension, $expected_extensions)) { |
|
49
|
2 |
|
$this->element->setRuleError($message); |
|
50
|
2 |
|
return false; |
|
51
|
|
|
} |
|
52
|
1 |
|
return true; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
3 |
|
private function parseOptions(int|array|string $opts): array |
|
56
|
|
|
{ |
|
57
|
3 |
|
if (!is_array($opts)) { |
|
|
|
|
|
|
58
|
1 |
|
$opts = (array)$opts; |
|
59
|
1 |
|
$opts[1] = null; |
|
60
|
|
|
} |
|
61
|
3 |
|
list($param, $message) = $opts; |
|
62
|
|
|
|
|
63
|
3 |
|
Assert::nullOrString($message); |
|
64
|
|
|
|
|
65
|
|
|
return [ |
|
66
|
3 |
|
'param' => $param, |
|
67
|
|
|
'message' => $message |
|
68
|
|
|
]; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|