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: 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: public function setValue($value)
58: {
59: if (is_array($value)) {
60: $this->value = new HttpUploadedFile($value);
61:
62: } elseif ($value instanceof HttpUploadedFile) {
63: $this->value = $value;
64:
65: } else {
66: $this->value = new HttpUploadedFile(NULL);
67: }
68: return $this;
69: }
70:
71:
72: 73: 74: 75:
76: public function isFilled()
77: {
78: return $this->value instanceof HttpUploadedFile && $this->value->isOK();
79: }
80:
81:
82: 83: 84: 85: 86: 87:
88: public static function validateFileSize(UploadControl $control, $limit)
89: {
90: $file = $control->getValue();
91: return $file instanceof HttpUploadedFile && $file->getSize() <= $limit;
92: }
93:
94:
95: 96: 97: 98: 99: 100:
101: public static function validateMimeType(UploadControl $control, $mimeType)
102: {
103: $file = $control->getValue();
104: if ($file instanceof HttpUploadedFile) {
105: $type = strtolower($file->getContentType());
106: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
107: if (in_array($type, $mimeTypes, TRUE)) {
108: return TRUE;
109: }
110: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
111: return TRUE;
112: }
113: }
114: return FALSE;
115: }
116:
117:
118: 119: 120: 121:
122: public static function validateImage(UploadControl $control)
123: {
124: $file = $control->getValue();
125: return $file instanceof HttpUploadedFile && $file->isImage();
126: }
127:
128: }
129: