1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: class FileUpload extends FormControl
21: {
22:
23: 24: 25:
26: public function __construct($label = NULL)
27: {
28: parent::__construct($label);
29: $this->control->type = 'file';
30: }
31:
32:
33:
34: 35: 36: 37: 38: 39:
40: protected function attached($form)
41: {
42: if ($form instanceof Form) {
43: if ($form->getMethod() !== Form::POST) {
44: throw new InvalidStateException('File upload requires method POST.');
45: }
46: $form->getElementPrototype()->enctype = 'multipart/form-data';
47: }
48: parent::attached($form);
49: }
50:
51:
52:
53: 54: 55: 56: 57:
58: public function setValue($value)
59: {
60: if (is_array($value)) {
61: $this->value = new HttpUploadedFile($value);
62:
63: } elseif ($value instanceof HttpUploadedFile) {
64: $this->value = $value;
65:
66: } else {
67: $this->value = new HttpUploadedFile(NULL);
68: }
69: return $this;
70: }
71:
72:
73:
74: 75: 76: 77: 78:
79: public static function validateFilled(IFormControl $control)
80: {
81: $file = $control->getValue();
82: return $file instanceof HttpUploadedFile && $file->isOK();
83: }
84:
85:
86:
87: 88: 89: 90: 91: 92:
93: public static function validateFileSize(FileUpload $control, $limit)
94: {
95: $file = $control->getValue();
96: return $file instanceof HttpUploadedFile && $file->getSize() <= $limit;
97: }
98:
99:
100:
101: 102: 103: 104: 105: 106:
107: public static function validateMimeType(FileUpload $control, $mimeType)
108: {
109: $file = $control->getValue();
110: if ($file instanceof HttpUploadedFile) {
111: $type = strtolower($file->getContentType());
112: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
113: if (in_array($type, $mimeTypes, TRUE)) {
114: return TRUE;
115: }
116: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
117: return TRUE;
118: }
119: }
120: return FALSE;
121: }
122:
123:
124:
125: 126: 127: 128: 129:
130: public static function validateImage(FileUpload $control)
131: {
132: $file = $control->getValue();
133: return $file instanceof HttpUploadedFile && $file->isImage();
134: }
135:
136: }
137: