|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of slick/form package |
|
5
|
|
|
* |
|
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
7
|
|
|
* file that was distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Slick\Form\Input\Validator; |
|
11
|
|
|
|
|
12
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
|
13
|
|
|
use Slick\Form\Input\File; |
|
14
|
|
|
use Slick\Validator\AbstractValidator; |
|
15
|
|
|
use Slick\Validator\ValidatorInterface; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Required Upload validator |
|
19
|
|
|
* |
|
20
|
|
|
* @package Slick\Form\Input\Validator |
|
21
|
|
|
* @author Filipe Silva <[email protected]> |
|
22
|
|
|
*/ |
|
23
|
|
|
class RequiredUpload extends AbstractValidator implements ValidatorInterface |
|
24
|
|
|
{ |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Error messages |
|
28
|
|
|
* @var string[] |
|
29
|
|
|
*/ |
|
30
|
|
|
protected $uploadErrors = [ |
|
31
|
|
|
UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.', |
|
32
|
|
|
UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload. ', |
|
33
|
|
|
UPLOAD_ERR_NO_FILE => 'No file was uploaded.', |
|
34
|
|
|
UPLOAD_ERR_FORM_SIZE => 'Uploaded file exceeds the HTML form MAX_FILE_SIZE.', |
|
35
|
|
|
UPLOAD_ERR_INI_SIZE => 'Uploaded file exceeds the php.ini upload_max_filesize.', |
|
36
|
|
|
UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.', |
|
37
|
|
|
UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.', |
|
38
|
|
|
]; |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @var array Error messages templates |
|
42
|
|
|
*/ |
|
43
|
|
|
protected $messageTemplate = 'Required upload fail: %s'; |
|
44
|
|
|
|
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Returns true if and only if $value meets the validation requirements |
|
48
|
|
|
* |
|
49
|
|
|
* The context specified can be used in the validation process so that |
|
50
|
|
|
* the same value can be valid or invalid depending on that data. |
|
51
|
|
|
* |
|
52
|
|
|
* @param mixed $value |
|
53
|
|
|
* @param array|mixed|File $context |
|
54
|
|
|
* |
|
55
|
|
|
* @return bool |
|
56
|
|
|
*/ |
|
57
|
|
|
public function validates($value, $context = []) |
|
58
|
|
|
{ |
|
59
|
|
|
$valid = true; |
|
60
|
|
|
/** @var File $input */ |
|
61
|
|
|
$input = $context['input']; |
|
62
|
|
|
/** @var UploadedFileInterface $file */ |
|
63
|
|
|
$file = $input->getValue(); |
|
64
|
|
|
if ($file->getError() == UPLOAD_ERR_NO_FILE) { |
|
65
|
|
|
$valid = false; |
|
66
|
|
|
$this->addMessage( |
|
67
|
|
|
$this->messageTemplate, |
|
68
|
|
|
$this->uploadErrors[$file->getError()] |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
return $valid; |
|
72
|
|
|
} |
|
73
|
|
|
} |