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: public function isFilled()
79: {
80: return $this->value instanceof HttpUploadedFile && $this->value->isOK();
81: }
82:
83:
84:
85: 86: 87: 88: 89: 90:
91: public static function validateFileSize(FileUpload $control, $limit)
92: {
93: $file = $control->getValue();
94: return $file instanceof HttpUploadedFile && $file->getSize() <= $limit;
95: }
96:
97:
98:
99: 100: 101: 102: 103: 104:
105: public static function validateMimeType(FileUpload $control, $mimeType)
106: {
107: $file = $control->getValue();
108: if ($file instanceof HttpUploadedFile) {
109: $type = strtolower($file->getContentType());
110: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
111: if (in_array($type, $mimeTypes, TRUE)) {
112: return TRUE;
113: }
114: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
115: return TRUE;
116: }
117: }
118: return FALSE;
119: }
120:
121:
122:
123: 124: 125: 126: 127:
128: public static function validateImage(FileUpload $control)
129: {
130: $file = $control->getValue();
131: return $file instanceof HttpUploadedFile && $file->isImage();
132: }
133:
134: }
135: