Completed
Pull Request — master (#100)
by
unknown
01:26
created
src/bulletproof.php 2 patches
Indentation   +505 added lines, -505 removed lines patch added patch discarded remove patch
@@ -15,509 +15,509 @@
 block discarded – undo
15 15
 
16 16
 class Image implements \ArrayAccess
17 17
 {
18
-    /**
19
-     * @var string The new image name, to be provided or will be generated
20
-     */
21
-    protected $name;
22
-
23
-    /**
24
-     * @var int The image width in pixels
25
-     */
26
-    protected $width;
27
-
28
-    /**
29
-     * @var int The image height in pixels
30
-     */
31
-    protected $height;
32
-
33
-    /**
34
-     * @var string The image mime type (extension)
35
-     */
36
-    protected $mime;
37
-
38
-    /**
39
-     * @var string The full image path (dir + image + mime)
40
-     */
41
-    protected $fullPath;
42
-
43
-    /**
44
-     * @var string The folder or image storage location
45
-     */
46
-    protected $location;
47
-
48
-    /**
49
-     * @var array The min and max image size allowed for upload (in bytes)
50
-     */
51
-    protected $size = array(100, 500000);
52
-
53
-    /**
54
-     * @var array The max height and width image allowed
55
-     */
56
-    protected $dimensions = array(5000, 5000);
57
-
58
-    /**
59
-     * @var array The mime types allowed for upload
60
-     */
61
-    protected $mimeTypes = array('jpeg', 'png', 'gif', 'jpg');
62
-
63
-    /**
64
-     * @var array list of known image types
65
-     */
66
-    protected $acceptedMimes = array(
67
-      1 => 'gif', 'jpeg', 'png', 'swf', 'psd',
68
-      'bmp', 'tiff', 'tiff', 'jpc', 'jp2', 'jpx',
69
-      'jb2', 'swc', 'iff', 'wbmp', 'xbm', 'ico',
70
-    );
71
-
72
-    /**
73
-     * @var string The language
74
-     */
75
-    protected $language = 'en';
76
-
77
-    /**
78
-     * @var array error messages strings
79
-     */
80
-    protected $commonUploadErrors = array(
81
-      'en' => array(
82
-        UPLOAD_ERR_OK => '',
83
-        UPLOAD_ERR_INI_SIZE => 'Image is larger than the specified amount set by the server',
84
-        UPLOAD_ERR_FORM_SIZE => 'Image is larger than the specified amount specified by browser',
85
-        UPLOAD_ERR_PARTIAL => 'Image could not be fully uploaded. Please try again later',
86
-        UPLOAD_ERR_NO_FILE => 'Image is not found',
87
-        UPLOAD_ERR_NO_TMP_DIR => 'Can\'t write to disk, due to server configuration ( No tmp dir found )',
88
-        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk. Please check you file permissions',
89
-        UPLOAD_ERR_EXTENSION => 'A PHP extension has halted this file upload process',
90
-
91
-        'ERROR_01' => 'Function \'exif_imagetype\' Not found. Please enable \'php_exif\' in your php.ini',
92
-        'ERROR_02' => 'No file input found with name: (%1$s)',
93
-        'ERROR_03' => 'Invalid dimension! Values must be integers',
94
-        'ERROR_04' => 'Can not create a directory (%1$s), please check write permission',
95
-        'ERROR_05' => 'Error! directory (%1$s) could not be created',
96
-        'ERROR_06' => 'Invalid File! Only (%1$s) image types are allowed',
97
-        'ERROR_07' => 'Image size should be minumum %1$s, upto maximum %2$s',
98
-        'ERROR_08' => 'Image height/width should be less than %1$s/%2$s pixels',
99
-        'ERROR_09' => 'Error! the language does not exist',
100
-      ),
101
-      'es' => array(
102
-        UPLOAD_ERR_OK => '',
103
-        UPLOAD_ERR_INI_SIZE => 'La imagen es más larga que la cantidad especificada por el servidor',
104
-        UPLOAD_ERR_FORM_SIZE => 'La imagen es mayor que la cantidad especificada por el navegador',
105
-        UPLOAD_ERR_PARTIAL => 'La imagen no fue completamente subida. Por favor inténtalo de nuevo más tarde',
106
-        UPLOAD_ERR_NO_FILE => 'La imagen no fue encontrada',
107
-        UPLOAD_ERR_NO_TMP_DIR => 'No se puede escribir en el disco debido a la configuración del servidor (directorio tmp no fue encontrado)',
108
-        UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir en el disco. Por favor verifique sus permisos',
109
-        UPLOAD_ERR_EXTENSION => 'Una extensión de PHP ha interrumpido el proceso de subida del archivo',
110
-
111
-        'ERROR_01' => 'La función \'exif_imagetype\' no fue encontrada. Por favor habilita \'php_exif\' en php.ini',
112
-        'ERROR_02' => 'No se pudo encontrar el archivo de entrada con nombre: (%1$s)',
113
-        'ERROR_03' => 'Dimensiones inválidas! Los valores necesitan ser enteros',
114
-        'ERROR_04' => 'No se pudo crear el directorio (%1$s), por favor revisa los permisos de escritura',
115
-        'ERROR_05' => 'Error! directorio (%1$s) no pudo ser creado',
116
-        'ERROR_06' => 'Archivo inválido! Solo los tipos de imagen (%1$s) son permitidos',
117
-        'ERROR_07' => 'La imagen necesita ser por lo menos %1$s, y un máximo %2$s',
118
-        'ERROR_08' => 'El largo y ancho de la imagen necesita ser menos que %1$s/%2$s pixeles',
119
-        'ERROR_09' => 'Error! El idioma no existe',
120
-      ),
121
-    );
122
-
123
-    /**
124
-     * @var array storage for the global array
125
-     */
126
-    private $_files = array();
127
-
128
-    /**
129
-     * @var string storage for any errors
130
-     */
131
-    private $error = '';
132
-
133
-    /**
134
-     * @param array $_files represents the $_FILES array passed as dependency
135
-     */
136
-    public function __construct(array $_files = array())
137
-    {
138
-      if (!function_exists('exif_imagetype')) {
139
-        $this->error = $this->commonUploadErrors[$this->language]['ERROR_01'];
140
-      }
141
-
142
-      $this->_files = $_files;
143
-    }
144
-
145
-    /**
146
-     * \ArrayAccess unused method
147
-     * 
148
-     * @param mixed $offset
149
-     * @param mixed $value
150
-     */
151
-    public function offsetSet($offset, $value) {}
152
-
153
-    /**
154
-     * \ArrayAccess unused method
155
-     * 
156
-     * @param mixed $offset
157
-     */
158
-    public function offsetExists($offset){}
159
-
160
-    /**
161
-     * \ArrayAccess unused method
162
-     * 
163
-     * @param mixed $offset
164
-     */
165
-    public function offsetUnset($offset){}
166
-
167
-    /**
168
-     * \ArrayAccess - get array value from object
169
-     *
170
-     * @param mixed $offset
171
-     *
172
-     * @return string|bool
173
-     */
174
-    public function offsetGet($offset)
175
-    {
176
-      // return false if $_FILES['key'] isn't found
177
-      if (!isset($this->_files[$offset])) {
178
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_02'], $offset);
179
-        return false;
180
-      }
181
-
182
-      $this->_files = $this->_files[$offset];
183
-
184
-      // check for common upload errors
185
-      if (isset($this->_files['error'])) {
186
-        $this->error = $this->commonUploadErrors[$this->language][$this->_files['error']];
187
-      }
188
-
189
-      return true;
190
-    }
191
-
192
-    /**
193
-     * Sets max image height and width limit.
194
-     *
195
-     * @param $maxWidth int max width value
196
-     * @param $maxHeight int max height value
197
-     *
198
-     * @return $this
199
-     */
200
-    public function setDimension($maxWidth, $maxHeight)
201
-    {
202
-      if ( (int) $maxWidth && (int) $maxHeight) {
203
-        $this->dimensions = array($maxWidth, $maxHeight);
204
-      } else {
205
-        $this->error = $this->commonUploadErrors[$this->language]['ERROR_03'];
206
-      }
207
-
208
-      return $this;
209
-    }
210
-
211
-    /**
212
-     * Returns the full path of the image ex 'location/image.mime'.
213
-     *
214
-     * @return string
215
-     */
216
-    public function getFullPath()
217
-    {
218
-      return $this->fullPath = $this->getLocation().'/'.$this->getName().'.'.$this->getMime();
219
-    }
220
-
221
-    /**
222
-     * Define a language
223
-     *
224
-     * @param $lang string language code 
225
-     *
226
-     * @return $this
227
-     */
228
-    public function setLanguage($lang)
229
-    {
230
-      if (isset($this->commonUploadErrors[$lang])) {
231
-        $this->language = $lang;
232
-      } else {
233
-        $this->error = $this->commonUploadErrors[$this->language]['ERROR_09'];
234
-      }
235
-
236
-      return $this;
237
-    }
238
-
239
-    /**
240
-     * Returns the image size in bytes.
241
-     *
242
-     * @return int
243
-     */
244
-    public function getSize()
245
-    {
246
-      return (int) $this->_files['size'];
247
-    }
248
-
249
-    /**
250
-     * Define a min and max image size for uploading.
251
-     *
252
-     * @param $min int minimum value in bytes
253
-     * @param $max int maximum value in bytes
254
-     *
255
-     * @return $this
256
-     */
257
-    public function setSize($min, $max)
258
-    {
259
-      $this->size = array($min, $max);
260
-      return $this;
261
-    }
262
-
263
-    /**
264
-     * Returns a JSON format of the image width, height, name, mime ...
265
-     *
266
-     * @return string
267
-     */
268
-    public function getJson()
269
-    {
270
-      return json_encode(
271
-        array(
272
-          'name' => $this->name,
273
-          'mime' => $this->mime,
274
-          'height' => $this->height,
275
-          'width' => $this->width,
276
-          'size' => $this->_files['size'],
277
-          'location' => $this->location,
278
-          'fullpath' => $this->fullPath,
279
-        )
280
-      );
281
-    }
282
-
283
-    /**
284
-     * Returns the image mime type.
285
-     *
286
-     * @return null|string
287
-     */
288
-    public function getMime()
289
-    {
290
-      if (!$this->mime) {
291
-        $this->mime = $this->getImageMime($this->_files['tmp_name']);
292
-      }
293
-
294
-      return $this->mime;
295
-    }
296
-
297
-    /**
298
-     * Define a mime type for uploading.
299
-     *
300
-     * @param array $fileTypes
301
-     *
302
-     * @return $this
303
-     */
304
-    public function setMime(array $fileTypes)
305
-    {
306
-      $this->mimeTypes = $fileTypes;
307
-      return $this;
308
-    }
309
-
310
-    /**
311
-     * Gets the real image mime type.
312
-     *
313
-     * @param $tmp_name string The upload tmp directory
314
-     *
315
-     * @return null|string
316
-     */
317
-    protected function getImageMime($tmp_name)
318
-    {
319
-      $this->mime = @$this->acceptedMimes[exif_imagetype($tmp_name)];
320
-      if (!$this->mime) {
321
-        return null;
322
-      }
323
-
324
-      return $this->mime;
325
-    }
326
-
327
-    /**
328
-     * Returns error string
329
-     *
330
-     * @return string
331
-     */
332
-    public function getError()
333
-    {
334
-      return $this->error;
335
-    }
336
-
337
-    /**
338
-     * Returns the image name.
339
-     *
340
-     * @return string
341
-     */
342
-    public function getName()
343
-    {
344
-      if (!$this->name) {
345
-        $this->name = uniqid('', true).'_'.str_shuffle(implode(range('e', 'q')));
346
-      }
347
-
348
-      return $this->name;
349
-    }
350
-
351
-    /**
352
-     * Provide image name if not provided.
353
-     *
354
-     * @param null $isNameProvided
355
-     *
356
-     * @return $this
357
-     */
358
-    public function setName($isNameProvided = null)
359
-    {
360
-      if ($isNameProvided) {
361
-        $this->name = filter_var($isNameProvided, FILTER_SANITIZE_STRING);
362
-      }
363
-
364
-      return $this;
365
-    }
366
-
367
-    /**
368
-     * Returns the image width.
369
-     *
370
-     * @return int
371
-     */
372
-    public function getWidth()
373
-    {
374
-      if ($this->width != null) {
375
-        return $this->width;
376
-      }
377
-
378
-      list($width) = getimagesize($this->_files['tmp_name']);
379
-
380
-      return $width;
381
-    }
382
-
383
-    /**
384
-     * Returns the image height in pixels.
385
-     *
386
-     * @return int
387
-     */
388
-    public function getHeight()
389
-    {
390
-      if ($this->height != null) {
391
-        return $this->height;
392
-      }
393
-
394
-      list(, $height) = getimagesize($this->_files['tmp_name']);
395
-
396
-      return $height;
397
-    }
398
-
399
-    /**
400
-     * Returns the storage / folder name.
401
-     *
402
-     * @return string
403
-     */
404
-    public function getLocation()
405
-    {
406
-      if (!$this->location) {
407
-        $this->setLocation();
408
-      }
409
-
410
-      return $this->location;
411
-    }
412
-
413
-    /**
414
-     * Validate directory/permission before creating a folder.
415
-     *
416
-     * @param $dir string the folder name to check
417
-     *
418
-     * @return bool
419
-     */
420
-    private function isDirectoryValid($dir)
421
-    {
422
-      return !file_exists($dir) && !is_dir($dir) || is_writable($dir);
423
-    }
424
-
425
-    /**
426
-     * Creates a location for upload storage.
427
-     *
428
-     * @param $dir string the folder name to create
429
-     * @param int $permission chmod permission
430
-     *
431
-     * @return $this
432
-     */
433
-    public function setLocation($dir = 'bulletproof', $permission = 0666)
434
-    {
435
-      $isDirectoryValid = $this->isDirectoryValid($dir);
436
-
437
-      if (!$isDirectoryValid) {
438
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_04'], $dir);
439
-        return false;
440
-      }
441
-
442
-      $create = !is_dir($dir) ? @mkdir('' . $dir, (int) $permission, true) : true;
443
-
444
-      if (!$create) {
445
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_05'], $dir);
446
-        return false;
447
-      }
448
-
449
-      $this->location = $dir;
450
-
451
-      return $this;
452
-    }
453
-
454
-    /**
455
-     * Validate image size, dimension or mimetypes
456
-     *
457
-     * @return boolean
458
-     */
459
-    protected function contraintsValidator()
460
-    {
461
-      /* check image for valid mime types and return mime */
462
-      $this->getImageMime($this->_files['tmp_name']);
463
-      /* validate image mime type */
464
-      if (!in_array($this->mime, $this->mimeTypes)) {
465
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_06'], implode(', ', $this->mimeTypes));
466
-        return false;
467
-      }
468
-
469
-      /* get image sizes */
470
-      list($minSize, $maxSize) = $this->size;
471
-
472
-      /* check image size based on the settings */
473
-      if ($this->_files['size'] < $minSize || $this->_files['size'] > $maxSize) {
474
-        $min = $minSize.' bytes ('.intval($minSize / 1000).' kb)';
475
-        $max = $maxSize.' bytes ('.intval($maxSize / 1000).' kb)';
476
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_07'], $min, $max);
477
-        return false;
478
-      }
479
-
480
-      /* check image dimension */
481
-      list($maxWidth, $maxHeight) = $this->dimensions;
482
-      $this->width = $this->getWidth();
483
-      $this->height = $this->getHeight();
484
-
485
-      if ($this->height > $maxHeight || $this->width > $maxWidth) {
486
-        $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_08'], $maxHeight, $maxWidth);
487
-        return false;
488
-      }
489
-
490
-      return true;
491
-    }
492
-
493
-    /**
494
-     * Validate and save (upload) file
495
-     *
496
-     * @return false|Image
497
-     */
498
-    public function upload()
499
-    {
500
-      if ($this->error !== '') {
501
-        return false;
502
-      }
503
-
504
-      $isValid = $this->contraintsValidator();
505
-
506
-      $isSuccess = $isValid && $this->isSaved($this->_files['tmp_name'], $this->getFullPath());
507
-
508
-      return $isSuccess ? $this : false;
509
-    }
510
-
511
-    /**
512
-     * Final upload method to be called, isolated for testing purposes.
513
-     *
514
-     * @param $tmp_name int the temporary location of the image file
515
-     * @param $destination int upload destination
516
-     *
517
-     * @return bool
518
-     */
519
-    protected function isSaved($tmp_name, $destination)
520
-    {
521
-      return move_uploaded_file($tmp_name, $destination);
522
-    }
18
+	/**
19
+	 * @var string The new image name, to be provided or will be generated
20
+	 */
21
+	protected $name;
22
+
23
+	/**
24
+	 * @var int The image width in pixels
25
+	 */
26
+	protected $width;
27
+
28
+	/**
29
+	 * @var int The image height in pixels
30
+	 */
31
+	protected $height;
32
+
33
+	/**
34
+	 * @var string The image mime type (extension)
35
+	 */
36
+	protected $mime;
37
+
38
+	/**
39
+	 * @var string The full image path (dir + image + mime)
40
+	 */
41
+	protected $fullPath;
42
+
43
+	/**
44
+	 * @var string The folder or image storage location
45
+	 */
46
+	protected $location;
47
+
48
+	/**
49
+	 * @var array The min and max image size allowed for upload (in bytes)
50
+	 */
51
+	protected $size = array(100, 500000);
52
+
53
+	/**
54
+	 * @var array The max height and width image allowed
55
+	 */
56
+	protected $dimensions = array(5000, 5000);
57
+
58
+	/**
59
+	 * @var array The mime types allowed for upload
60
+	 */
61
+	protected $mimeTypes = array('jpeg', 'png', 'gif', 'jpg');
62
+
63
+	/**
64
+	 * @var array list of known image types
65
+	 */
66
+	protected $acceptedMimes = array(
67
+	  1 => 'gif', 'jpeg', 'png', 'swf', 'psd',
68
+	  'bmp', 'tiff', 'tiff', 'jpc', 'jp2', 'jpx',
69
+	  'jb2', 'swc', 'iff', 'wbmp', 'xbm', 'ico',
70
+	);
71
+
72
+	/**
73
+	 * @var string The language
74
+	 */
75
+	protected $language = 'en';
76
+
77
+	/**
78
+	 * @var array error messages strings
79
+	 */
80
+	protected $commonUploadErrors = array(
81
+	  'en' => array(
82
+		UPLOAD_ERR_OK => '',
83
+		UPLOAD_ERR_INI_SIZE => 'Image is larger than the specified amount set by the server',
84
+		UPLOAD_ERR_FORM_SIZE => 'Image is larger than the specified amount specified by browser',
85
+		UPLOAD_ERR_PARTIAL => 'Image could not be fully uploaded. Please try again later',
86
+		UPLOAD_ERR_NO_FILE => 'Image is not found',
87
+		UPLOAD_ERR_NO_TMP_DIR => 'Can\'t write to disk, due to server configuration ( No tmp dir found )',
88
+		UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk. Please check you file permissions',
89
+		UPLOAD_ERR_EXTENSION => 'A PHP extension has halted this file upload process',
90
+
91
+		'ERROR_01' => 'Function \'exif_imagetype\' Not found. Please enable \'php_exif\' in your php.ini',
92
+		'ERROR_02' => 'No file input found with name: (%1$s)',
93
+		'ERROR_03' => 'Invalid dimension! Values must be integers',
94
+		'ERROR_04' => 'Can not create a directory (%1$s), please check write permission',
95
+		'ERROR_05' => 'Error! directory (%1$s) could not be created',
96
+		'ERROR_06' => 'Invalid File! Only (%1$s) image types are allowed',
97
+		'ERROR_07' => 'Image size should be minumum %1$s, upto maximum %2$s',
98
+		'ERROR_08' => 'Image height/width should be less than %1$s/%2$s pixels',
99
+		'ERROR_09' => 'Error! the language does not exist',
100
+	  ),
101
+	  'es' => array(
102
+		UPLOAD_ERR_OK => '',
103
+		UPLOAD_ERR_INI_SIZE => 'La imagen es más larga que la cantidad especificada por el servidor',
104
+		UPLOAD_ERR_FORM_SIZE => 'La imagen es mayor que la cantidad especificada por el navegador',
105
+		UPLOAD_ERR_PARTIAL => 'La imagen no fue completamente subida. Por favor inténtalo de nuevo más tarde',
106
+		UPLOAD_ERR_NO_FILE => 'La imagen no fue encontrada',
107
+		UPLOAD_ERR_NO_TMP_DIR => 'No se puede escribir en el disco debido a la configuración del servidor (directorio tmp no fue encontrado)',
108
+		UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir en el disco. Por favor verifique sus permisos',
109
+		UPLOAD_ERR_EXTENSION => 'Una extensión de PHP ha interrumpido el proceso de subida del archivo',
110
+
111
+		'ERROR_01' => 'La función \'exif_imagetype\' no fue encontrada. Por favor habilita \'php_exif\' en php.ini',
112
+		'ERROR_02' => 'No se pudo encontrar el archivo de entrada con nombre: (%1$s)',
113
+		'ERROR_03' => 'Dimensiones inválidas! Los valores necesitan ser enteros',
114
+		'ERROR_04' => 'No se pudo crear el directorio (%1$s), por favor revisa los permisos de escritura',
115
+		'ERROR_05' => 'Error! directorio (%1$s) no pudo ser creado',
116
+		'ERROR_06' => 'Archivo inválido! Solo los tipos de imagen (%1$s) son permitidos',
117
+		'ERROR_07' => 'La imagen necesita ser por lo menos %1$s, y un máximo %2$s',
118
+		'ERROR_08' => 'El largo y ancho de la imagen necesita ser menos que %1$s/%2$s pixeles',
119
+		'ERROR_09' => 'Error! El idioma no existe',
120
+	  ),
121
+	);
122
+
123
+	/**
124
+	 * @var array storage for the global array
125
+	 */
126
+	private $_files = array();
127
+
128
+	/**
129
+	 * @var string storage for any errors
130
+	 */
131
+	private $error = '';
132
+
133
+	/**
134
+	 * @param array $_files represents the $_FILES array passed as dependency
135
+	 */
136
+	public function __construct(array $_files = array())
137
+	{
138
+	  if (!function_exists('exif_imagetype')) {
139
+		$this->error = $this->commonUploadErrors[$this->language]['ERROR_01'];
140
+	  }
141
+
142
+	  $this->_files = $_files;
143
+	}
144
+
145
+	/**
146
+	 * \ArrayAccess unused method
147
+	 * 
148
+	 * @param mixed $offset
149
+	 * @param mixed $value
150
+	 */
151
+	public function offsetSet($offset, $value) {}
152
+
153
+	/**
154
+	 * \ArrayAccess unused method
155
+	 * 
156
+	 * @param mixed $offset
157
+	 */
158
+	public function offsetExists($offset){}
159
+
160
+	/**
161
+	 * \ArrayAccess unused method
162
+	 * 
163
+	 * @param mixed $offset
164
+	 */
165
+	public function offsetUnset($offset){}
166
+
167
+	/**
168
+	 * \ArrayAccess - get array value from object
169
+	 *
170
+	 * @param mixed $offset
171
+	 *
172
+	 * @return string|bool
173
+	 */
174
+	public function offsetGet($offset)
175
+	{
176
+	  // return false if $_FILES['key'] isn't found
177
+	  if (!isset($this->_files[$offset])) {
178
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_02'], $offset);
179
+		return false;
180
+	  }
181
+
182
+	  $this->_files = $this->_files[$offset];
183
+
184
+	  // check for common upload errors
185
+	  if (isset($this->_files['error'])) {
186
+		$this->error = $this->commonUploadErrors[$this->language][$this->_files['error']];
187
+	  }
188
+
189
+	  return true;
190
+	}
191
+
192
+	/**
193
+	 * Sets max image height and width limit.
194
+	 *
195
+	 * @param $maxWidth int max width value
196
+	 * @param $maxHeight int max height value
197
+	 *
198
+	 * @return $this
199
+	 */
200
+	public function setDimension($maxWidth, $maxHeight)
201
+	{
202
+	  if ( (int) $maxWidth && (int) $maxHeight) {
203
+		$this->dimensions = array($maxWidth, $maxHeight);
204
+	  } else {
205
+		$this->error = $this->commonUploadErrors[$this->language]['ERROR_03'];
206
+	  }
207
+
208
+	  return $this;
209
+	}
210
+
211
+	/**
212
+	 * Returns the full path of the image ex 'location/image.mime'.
213
+	 *
214
+	 * @return string
215
+	 */
216
+	public function getFullPath()
217
+	{
218
+	  return $this->fullPath = $this->getLocation().'/'.$this->getName().'.'.$this->getMime();
219
+	}
220
+
221
+	/**
222
+	 * Define a language
223
+	 *
224
+	 * @param $lang string language code 
225
+	 *
226
+	 * @return $this
227
+	 */
228
+	public function setLanguage($lang)
229
+	{
230
+	  if (isset($this->commonUploadErrors[$lang])) {
231
+		$this->language = $lang;
232
+	  } else {
233
+		$this->error = $this->commonUploadErrors[$this->language]['ERROR_09'];
234
+	  }
235
+
236
+	  return $this;
237
+	}
238
+
239
+	/**
240
+	 * Returns the image size in bytes.
241
+	 *
242
+	 * @return int
243
+	 */
244
+	public function getSize()
245
+	{
246
+	  return (int) $this->_files['size'];
247
+	}
248
+
249
+	/**
250
+	 * Define a min and max image size for uploading.
251
+	 *
252
+	 * @param $min int minimum value in bytes
253
+	 * @param $max int maximum value in bytes
254
+	 *
255
+	 * @return $this
256
+	 */
257
+	public function setSize($min, $max)
258
+	{
259
+	  $this->size = array($min, $max);
260
+	  return $this;
261
+	}
262
+
263
+	/**
264
+	 * Returns a JSON format of the image width, height, name, mime ...
265
+	 *
266
+	 * @return string
267
+	 */
268
+	public function getJson()
269
+	{
270
+	  return json_encode(
271
+		array(
272
+		  'name' => $this->name,
273
+		  'mime' => $this->mime,
274
+		  'height' => $this->height,
275
+		  'width' => $this->width,
276
+		  'size' => $this->_files['size'],
277
+		  'location' => $this->location,
278
+		  'fullpath' => $this->fullPath,
279
+		)
280
+	  );
281
+	}
282
+
283
+	/**
284
+	 * Returns the image mime type.
285
+	 *
286
+	 * @return null|string
287
+	 */
288
+	public function getMime()
289
+	{
290
+	  if (!$this->mime) {
291
+		$this->mime = $this->getImageMime($this->_files['tmp_name']);
292
+	  }
293
+
294
+	  return $this->mime;
295
+	}
296
+
297
+	/**
298
+	 * Define a mime type for uploading.
299
+	 *
300
+	 * @param array $fileTypes
301
+	 *
302
+	 * @return $this
303
+	 */
304
+	public function setMime(array $fileTypes)
305
+	{
306
+	  $this->mimeTypes = $fileTypes;
307
+	  return $this;
308
+	}
309
+
310
+	/**
311
+	 * Gets the real image mime type.
312
+	 *
313
+	 * @param $tmp_name string The upload tmp directory
314
+	 *
315
+	 * @return null|string
316
+	 */
317
+	protected function getImageMime($tmp_name)
318
+	{
319
+	  $this->mime = @$this->acceptedMimes[exif_imagetype($tmp_name)];
320
+	  if (!$this->mime) {
321
+		return null;
322
+	  }
323
+
324
+	  return $this->mime;
325
+	}
326
+
327
+	/**
328
+	 * Returns error string
329
+	 *
330
+	 * @return string
331
+	 */
332
+	public function getError()
333
+	{
334
+	  return $this->error;
335
+	}
336
+
337
+	/**
338
+	 * Returns the image name.
339
+	 *
340
+	 * @return string
341
+	 */
342
+	public function getName()
343
+	{
344
+	  if (!$this->name) {
345
+		$this->name = uniqid('', true).'_'.str_shuffle(implode(range('e', 'q')));
346
+	  }
347
+
348
+	  return $this->name;
349
+	}
350
+
351
+	/**
352
+	 * Provide image name if not provided.
353
+	 *
354
+	 * @param null $isNameProvided
355
+	 *
356
+	 * @return $this
357
+	 */
358
+	public function setName($isNameProvided = null)
359
+	{
360
+	  if ($isNameProvided) {
361
+		$this->name = filter_var($isNameProvided, FILTER_SANITIZE_STRING);
362
+	  }
363
+
364
+	  return $this;
365
+	}
366
+
367
+	/**
368
+	 * Returns the image width.
369
+	 *
370
+	 * @return int
371
+	 */
372
+	public function getWidth()
373
+	{
374
+	  if ($this->width != null) {
375
+		return $this->width;
376
+	  }
377
+
378
+	  list($width) = getimagesize($this->_files['tmp_name']);
379
+
380
+	  return $width;
381
+	}
382
+
383
+	/**
384
+	 * Returns the image height in pixels.
385
+	 *
386
+	 * @return int
387
+	 */
388
+	public function getHeight()
389
+	{
390
+	  if ($this->height != null) {
391
+		return $this->height;
392
+	  }
393
+
394
+	  list(, $height) = getimagesize($this->_files['tmp_name']);
395
+
396
+	  return $height;
397
+	}
398
+
399
+	/**
400
+	 * Returns the storage / folder name.
401
+	 *
402
+	 * @return string
403
+	 */
404
+	public function getLocation()
405
+	{
406
+	  if (!$this->location) {
407
+		$this->setLocation();
408
+	  }
409
+
410
+	  return $this->location;
411
+	}
412
+
413
+	/**
414
+	 * Validate directory/permission before creating a folder.
415
+	 *
416
+	 * @param $dir string the folder name to check
417
+	 *
418
+	 * @return bool
419
+	 */
420
+	private function isDirectoryValid($dir)
421
+	{
422
+	  return !file_exists($dir) && !is_dir($dir) || is_writable($dir);
423
+	}
424
+
425
+	/**
426
+	 * Creates a location for upload storage.
427
+	 *
428
+	 * @param $dir string the folder name to create
429
+	 * @param int $permission chmod permission
430
+	 *
431
+	 * @return $this
432
+	 */
433
+	public function setLocation($dir = 'bulletproof', $permission = 0666)
434
+	{
435
+	  $isDirectoryValid = $this->isDirectoryValid($dir);
436
+
437
+	  if (!$isDirectoryValid) {
438
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_04'], $dir);
439
+		return false;
440
+	  }
441
+
442
+	  $create = !is_dir($dir) ? @mkdir('' . $dir, (int) $permission, true) : true;
443
+
444
+	  if (!$create) {
445
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_05'], $dir);
446
+		return false;
447
+	  }
448
+
449
+	  $this->location = $dir;
450
+
451
+	  return $this;
452
+	}
453
+
454
+	/**
455
+	 * Validate image size, dimension or mimetypes
456
+	 *
457
+	 * @return boolean
458
+	 */
459
+	protected function contraintsValidator()
460
+	{
461
+	  /* check image for valid mime types and return mime */
462
+	  $this->getImageMime($this->_files['tmp_name']);
463
+	  /* validate image mime type */
464
+	  if (!in_array($this->mime, $this->mimeTypes)) {
465
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_06'], implode(', ', $this->mimeTypes));
466
+		return false;
467
+	  }
468
+
469
+	  /* get image sizes */
470
+	  list($minSize, $maxSize) = $this->size;
471
+
472
+	  /* check image size based on the settings */
473
+	  if ($this->_files['size'] < $minSize || $this->_files['size'] > $maxSize) {
474
+		$min = $minSize.' bytes ('.intval($minSize / 1000).' kb)';
475
+		$max = $maxSize.' bytes ('.intval($maxSize / 1000).' kb)';
476
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_07'], $min, $max);
477
+		return false;
478
+	  }
479
+
480
+	  /* check image dimension */
481
+	  list($maxWidth, $maxHeight) = $this->dimensions;
482
+	  $this->width = $this->getWidth();
483
+	  $this->height = $this->getHeight();
484
+
485
+	  if ($this->height > $maxHeight || $this->width > $maxWidth) {
486
+		$this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_08'], $maxHeight, $maxWidth);
487
+		return false;
488
+	  }
489
+
490
+	  return true;
491
+	}
492
+
493
+	/**
494
+	 * Validate and save (upload) file
495
+	 *
496
+	 * @return false|Image
497
+	 */
498
+	public function upload()
499
+	{
500
+	  if ($this->error !== '') {
501
+		return false;
502
+	  }
503
+
504
+	  $isValid = $this->contraintsValidator();
505
+
506
+	  $isSuccess = $isValid && $this->isSaved($this->_files['tmp_name'], $this->getFullPath());
507
+
508
+	  return $isSuccess ? $this : false;
509
+	}
510
+
511
+	/**
512
+	 * Final upload method to be called, isolated for testing purposes.
513
+	 *
514
+	 * @param $tmp_name int the temporary location of the image file
515
+	 * @param $destination int upload destination
516
+	 *
517
+	 * @return bool
518
+	 */
519
+	protected function isSaved($tmp_name, $destination)
520
+	{
521
+	  return move_uploaded_file($tmp_name, $destination);
522
+	}
523 523
 }
Please login to merge, or discard this patch.
Braces   +22 added lines, -44 removed lines patch added patch discarded remove patch
@@ -133,8 +133,7 @@  discard block
 block discarded – undo
133 133
     /**
134 134
      * @param array $_files represents the $_FILES array passed as dependency
135 135
      */
136
-    public function __construct(array $_files = array())
137
-    {
136
+    public function __construct(array $_files = array()) {
138 137
       if (!function_exists('exif_imagetype')) {
139 138
         $this->error = $this->commonUploadErrors[$this->language]['ERROR_01'];
140 139
       }
@@ -171,8 +170,7 @@  discard block
 block discarded – undo
171 170
      *
172 171
      * @return string|bool
173 172
      */
174
-    public function offsetGet($offset)
175
-    {
173
+    public function offsetGet($offset) {
176 174
       // return false if $_FILES['key'] isn't found
177 175
       if (!isset($this->_files[$offset])) {
178 176
         $this->error = sprintf($this->commonUploadErrors[$this->language]['ERROR_02'], $offset);
@@ -197,8 +195,7 @@  discard block
 block discarded – undo
197 195
      *
198 196
      * @return $this
199 197
      */
200
-    public function setDimension($maxWidth, $maxHeight)
201
-    {
198
+    public function setDimension($maxWidth, $maxHeight) {
202 199
       if ( (int) $maxWidth && (int) $maxHeight) {
203 200
         $this->dimensions = array($maxWidth, $maxHeight);
204 201
       } else {
@@ -213,8 +210,7 @@  discard block
 block discarded – undo
213 210
      *
214 211
      * @return string
215 212
      */
216
-    public function getFullPath()
217
-    {
213
+    public function getFullPath() {
218 214
       return $this->fullPath = $this->getLocation().'/'.$this->getName().'.'.$this->getMime();
219 215
     }
220 216
 
@@ -225,8 +221,7 @@  discard block
 block discarded – undo
225 221
      *
226 222
      * @return $this
227 223
      */
228
-    public function setLanguage($lang)
229
-    {
224
+    public function setLanguage($lang) {
230 225
       if (isset($this->commonUploadErrors[$lang])) {
231 226
         $this->language = $lang;
232 227
       } else {
@@ -241,8 +236,7 @@  discard block
 block discarded – undo
241 236
      *
242 237
      * @return int
243 238
      */
244
-    public function getSize()
245
-    {
239
+    public function getSize() {
246 240
       return (int) $this->_files['size'];
247 241
     }
248 242
 
@@ -254,8 +248,7 @@  discard block
 block discarded – undo
254 248
      *
255 249
      * @return $this
256 250
      */
257
-    public function setSize($min, $max)
258
-    {
251
+    public function setSize($min, $max) {
259 252
       $this->size = array($min, $max);
260 253
       return $this;
261 254
     }
@@ -265,8 +258,7 @@  discard block
 block discarded – undo
265 258
      *
266 259
      * @return string
267 260
      */
268
-    public function getJson()
269
-    {
261
+    public function getJson() {
270 262
       return json_encode(
271 263
         array(
272 264
           'name' => $this->name,
@@ -285,8 +277,7 @@  discard block
 block discarded – undo
285 277
      *
286 278
      * @return null|string
287 279
      */
288
-    public function getMime()
289
-    {
280
+    public function getMime() {
290 281
       if (!$this->mime) {
291 282
         $this->mime = $this->getImageMime($this->_files['tmp_name']);
292 283
       }
@@ -301,8 +292,7 @@  discard block
 block discarded – undo
301 292
      *
302 293
      * @return $this
303 294
      */
304
-    public function setMime(array $fileTypes)
305
-    {
295
+    public function setMime(array $fileTypes) {
306 296
       $this->mimeTypes = $fileTypes;
307 297
       return $this;
308 298
     }
@@ -314,8 +304,7 @@  discard block
 block discarded – undo
314 304
      *
315 305
      * @return null|string
316 306
      */
317
-    protected function getImageMime($tmp_name)
318
-    {
307
+    protected function getImageMime($tmp_name) {
319 308
       $this->mime = @$this->acceptedMimes[exif_imagetype($tmp_name)];
320 309
       if (!$this->mime) {
321 310
         return null;
@@ -329,8 +318,7 @@  discard block
 block discarded – undo
329 318
      *
330 319
      * @return string
331 320
      */
332
-    public function getError()
333
-    {
321
+    public function getError() {
334 322
       return $this->error;
335 323
     }
336 324
 
@@ -339,8 +327,7 @@  discard block
 block discarded – undo
339 327
      *
340 328
      * @return string
341 329
      */
342
-    public function getName()
343
-    {
330
+    public function getName() {
344 331
       if (!$this->name) {
345 332
         $this->name = uniqid('', true).'_'.str_shuffle(implode(range('e', 'q')));
346 333
       }
@@ -355,8 +342,7 @@  discard block
 block discarded – undo
355 342
      *
356 343
      * @return $this
357 344
      */
358
-    public function setName($isNameProvided = null)
359
-    {
345
+    public function setName($isNameProvided = null) {
360 346
       if ($isNameProvided) {
361 347
         $this->name = filter_var($isNameProvided, FILTER_SANITIZE_STRING);
362 348
       }
@@ -369,8 +355,7 @@  discard block
 block discarded – undo
369 355
      *
370 356
      * @return int
371 357
      */
372
-    public function getWidth()
373
-    {
358
+    public function getWidth() {
374 359
       if ($this->width != null) {
375 360
         return $this->width;
376 361
       }
@@ -385,8 +370,7 @@  discard block
 block discarded – undo
385 370
      *
386 371
      * @return int
387 372
      */
388
-    public function getHeight()
389
-    {
373
+    public function getHeight() {
390 374
       if ($this->height != null) {
391 375
         return $this->height;
392 376
       }
@@ -401,8 +385,7 @@  discard block
 block discarded – undo
401 385
      *
402 386
      * @return string
403 387
      */
404
-    public function getLocation()
405
-    {
388
+    public function getLocation() {
406 389
       if (!$this->location) {
407 390
         $this->setLocation();
408 391
       }
@@ -417,8 +400,7 @@  discard block
 block discarded – undo
417 400
      *
418 401
      * @return bool
419 402
      */
420
-    private function isDirectoryValid($dir)
421
-    {
403
+    private function isDirectoryValid($dir) {
422 404
       return !file_exists($dir) && !is_dir($dir) || is_writable($dir);
423 405
     }
424 406
 
@@ -430,8 +412,7 @@  discard block
 block discarded – undo
430 412
      *
431 413
      * @return $this
432 414
      */
433
-    public function setLocation($dir = 'bulletproof', $permission = 0666)
434
-    {
415
+    public function setLocation($dir = 'bulletproof', $permission = 0666) {
435 416
       $isDirectoryValid = $this->isDirectoryValid($dir);
436 417
 
437 418
       if (!$isDirectoryValid) {
@@ -456,8 +437,7 @@  discard block
 block discarded – undo
456 437
      *
457 438
      * @return boolean
458 439
      */
459
-    protected function contraintsValidator()
460
-    {
440
+    protected function contraintsValidator() {
461 441
       /* check image for valid mime types and return mime */
462 442
       $this->getImageMime($this->_files['tmp_name']);
463 443
       /* validate image mime type */
@@ -495,8 +475,7 @@  discard block
 block discarded – undo
495 475
      *
496 476
      * @return false|Image
497 477
      */
498
-    public function upload()
499
-    {
478
+    public function upload() {
500 479
       if ($this->error !== '') {
501 480
         return false;
502 481
       }
@@ -516,8 +495,7 @@  discard block
 block discarded – undo
516 495
      *
517 496
      * @return bool
518 497
      */
519
-    protected function isSaved($tmp_name, $destination)
520
-    {
498
+    protected function isSaved($tmp_name, $destination) {
521 499
       return move_uploaded_file($tmp_name, $destination);
522 500
     }
523 501
 }
Please login to merge, or discard this patch.