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