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: public static function validateFileSize(NUploadControl $control, $limit)
87: {
88: $file = $control->getValue();
89: return $file instanceof NHttpUploadedFile && $file->getSize() <= $limit;
90: }
91:
92:
93: 94: 95: 96: 97:
98: public static function validateMimeType(NUploadControl $control, $mimeType)
99: {
100: $file = $control->getValue();
101: if ($file instanceof NHttpUploadedFile) {
102: $type = strtolower($file->getContentType());
103: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
104: if (in_array($type, $mimeTypes, TRUE)) {
105: return TRUE;
106: }
107: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
108: return TRUE;
109: }
110: }
111: return FALSE;
112: }
113:
114:
115: 116: 117: 118: 119:
120: public static function validateImage(NUploadControl $control)
121: {
122: $file = $control->getValue();
123: return $file instanceof NHttpUploadedFile && $file->isImage();
124: }
125:
126: }
127: