|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Mbright\Validation\Rule\Validate; |
|
4
|
|
|
|
|
5
|
|
|
class Upload implements ValidateRuleInterface |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* Validates that the value is an array of file-upload information, and if a file is referred to, that is actually |
|
9
|
|
|
* an uploaded file. |
|
10
|
|
|
* |
|
11
|
|
|
* The required keys are 'error', 'name', 'size', 'tmp_name', 'type'. More or fewer or different keys than this will |
|
12
|
|
|
* return a "malformed" error. |
|
13
|
|
|
* |
|
14
|
|
|
* @param object $subject The subject to be filtered. |
|
15
|
|
|
* @param string $field The subject field name. |
|
16
|
|
|
* |
|
17
|
|
|
* @return bool True if valid, false if not. |
|
18
|
|
|
*/ |
|
19
|
18 |
|
public function __invoke($subject, string $field): bool |
|
20
|
|
|
{ |
|
21
|
18 |
|
$value = $subject->$field; |
|
22
|
|
|
|
|
23
|
18 |
|
$wellFormed = $this->preCheck($value); |
|
24
|
18 |
|
if (!$wellFormed) { |
|
25
|
6 |
|
return false; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
// was the upload explicitly ok? |
|
29
|
12 |
|
$err = $value['error']; |
|
30
|
12 |
|
if ($err != UPLOAD_ERR_OK) { |
|
31
|
6 |
|
return false; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
// is it actually an uploaded file? |
|
35
|
6 |
|
if (!$this->isUploadedFile($value['tmp_name'])) { |
|
36
|
3 |
|
return false; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
3 |
|
return true; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Check that the file-upload array is well-formed. |
|
44
|
|
|
* |
|
45
|
|
|
* @param array $value The file-upload array. |
|
46
|
|
|
* |
|
47
|
|
|
* @return bool |
|
48
|
|
|
*/ |
|
49
|
18 |
|
protected function preCheck(&$value) |
|
50
|
|
|
{ |
|
51
|
18 |
|
if (!is_array($value)) { |
|
|
|
|
|
|
52
|
3 |
|
return false; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
// presorted list of expected keys |
|
56
|
15 |
|
$expect = ['error', 'name', 'size', 'tmp_name', 'type']; |
|
57
|
|
|
|
|
58
|
|
|
// remove unexpected keys |
|
59
|
15 |
|
foreach ($value as $key => $val) { |
|
60
|
15 |
|
if (!in_array($key, $expect)) { |
|
61
|
15 |
|
unset($value[$key]); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
15 |
|
$actual = array_keys($value); |
|
66
|
15 |
|
sort($actual); |
|
67
|
15 |
|
if ($expect != $actual) { |
|
68
|
3 |
|
return false; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
12 |
|
return true; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* Check whether the file was uploaded via HTTP POST. |
|
76
|
|
|
* |
|
77
|
|
|
* @param string $file The file to check. |
|
78
|
|
|
* |
|
79
|
|
|
* @return bool True if the file was uploaded via HTTP POST, false if not. |
|
80
|
|
|
*/ |
|
81
|
6 |
|
protected function isUploadedFile($file) |
|
82
|
|
|
{ |
|
83
|
6 |
|
return is_uploaded_file($file); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|