1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: class NFileUpload extends NFormControl
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 NForm) {
44: if ($form->getMethod() !== NForm::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 NHttpUploadedFile($value);
63:
64: } elseif ($value instanceof NHttpUploadedFile) {
65: $this->value = $value;
66:
67: } else {
68: $this->value = new NHttpUploadedFile(NULL);
69: }
70: return $this;
71: }
72:
73:
74:
75: 76: 77: 78: 79:
80: public static function validateFilled(IFormControl $control)
81: {
82: $file = $control->getValue();
83: return $file instanceof NHttpUploadedFile && $file->isOK();
84: }
85:
86:
87:
88: 89: 90: 91: 92: 93:
94: public static function validateFileSize(NFileUpload $control, $limit)
95: {
96: $file = $control->getValue();
97: return $file instanceof NHttpUploadedFile && $file->getSize() <= $limit;
98: }
99:
100:
101:
102: 103: 104: 105: 106: 107:
108: public static function validateMimeType(NFileUpload $control, $mimeType)
109: {
110: $file = $control->getValue();
111: if ($file instanceof NHttpUploadedFile) {
112: $type = strtolower($file->getContentType());
113: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
114: if (in_array($type, $mimeTypes, TRUE)) {
115: return TRUE;
116: }
117: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
118: return TRUE;
119: }
120: }
121: return FALSE;
122: }
123:
124: }
125: