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