forked from phalcon/cphalcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MimeType.zep
124 lines (108 loc) · 2.96 KB
/
MimeType.zep
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalconphp.com>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
namespace Phalcon\Validation\Validator\File;
use Phalcon\Messages\Message;
use Phalcon\Validation;
use Phalcon\Validation\Validator\File\FileAbstract;
/**
* Phalcon\Validation\Validator\File
*
* Checks if a value has a correct file mime type
*
* <code>
* use Phalcon\Validation;
* use Phalcon\Validation\Validator\File\MimeType;
*
* $validator = new Validation();
*
* $validator->add(
* "file",
* new MimeType(
* [
* "types" => [
* "image/jpeg",
* "image/png",
* ],
* "message" => "Allowed file types are :types"
* ]
* )
* );
*
* $validator->add(
* [
* "file",
* "anotherFile",
* ],
* new MimeType(
* [
* "types" => [
* "file" => [
* "image/jpeg",
* "image/png",
* ],
* "anotherFile" => [
* "image/gif",
* "image/bmp",
* ],
* ],
* "message" => [
* "file" => "Allowed file types are image/jpeg and image/png",
* "anotherFile" => "Allowed file types are image/gif and image/bmp",
* ]
* ]
* )
* );
* </code>
*/
class MimeType extends FileAbstract
{
protected template = "File :field must be of type: :types";
/**
* Executes the validation
*
* @param Valiation $validation
* @param mixed $field
* @return bool
*/
public function validate(<Validation> validation, var field) -> bool
{
var fieldTypes, mime, replacePairs, tmp, types, value;
// Check file upload
if (this->checkUpload(validation, field) === false) {
return false;
}
let value = validation->getValue(field);
let types = this->getOption("types");
if fetch fieldTypes, types[field] {
let types = fieldTypes;
}
if unlikely typeof types != "array" {
throw new \Phalcon\Validation\Exception(
"Option 'allowedTypes' must be an array"
);
}
if function_exists("finfo_open") {
let tmp = finfo_open(FILEINFO_MIME_TYPE),
mime = finfo_file(tmp, value["tmp_name"]);
finfo_close(tmp);
} else {
let mime = value["type"];
}
if !in_array(mime, types) {
let replacePairs = [
":types": join(", ", types)
];
validation->appendMessage(
this->messageFactory(validation, field, replacePairs)
);
return false;
}
return true;
}
}