UploadedFileValidator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 64
ccs 23
cts 23
cp 1
rs 10
c 1
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A check() 0 19 3
A getMimeByExtension() 0 10 2
1
<?php
2
/**
3
 * Class for uploaded file validation
4
 *
5
 * @file      UploadedFileValidator.php
6
 *
7
 * PHP version 8.0+
8
 *
9
 * @author    Yancharuk Alexander <alex at itvault dot info>
10
 * @copyright © 2012-2021 Alexander Yancharuk
11
 * @date      2013-08-03 11:04
12
 * @license   The BSD 3-Clause License
13
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
14
 */
15
16
namespace Veles\Validators;
17
18
/**
19
 * Class UploadedFileValidator
20
 *
21
 * @author  Yancharuk Alexander <alex at itvault dot info>
22
 */
23
class UploadedFileValidator implements ValidatorInterface
24
{
25
	/** @var array */
26
	protected $allowed_extensions = [];
27
28
	/**
29
	 * Creates validator instance
30
	 *
31
	 * @param string $ext_string List of valid extension separated by comma
32
	 */
33 10
	public function __construct($ext_string = 'gif,jpg,jpeg,png')
34
	{
35 10
		$extensions = explode(',', $ext_string);
36
37 10
		foreach ($extensions as $extension) {
38 10
			$this->allowed_extensions[trim($extension)] = true;
39
		}
40
	}
41
42
	/**
43
	 * Uploaded file validation
44
	 *
45
	 * @param mixed $value Index name in $_FILE array
46
	 *
47
	 * @return bool
48
	 */
49 6
	public function check($value)
50
	{
51 6
		$file_name = strtolower($_FILES[$value]['name']);
52
53 6
		if (false === strpos($file_name, '.')) {
54 1
			return false;
55
		}
56
57 5
		$array    = explode('.', $file_name);
58 5
		$file_ext = strtolower(end($array));
59
60 5
		if (!isset($this->allowed_extensions[$file_ext])) {
61 1
			return false;
62
		}
63
64 4
		$real_mime = (new \finfo(FILEINFO_MIME))
65 4
			->file($_FILES[$value]['tmp_name']);
66
67 4
		return $real_mime === $this->getMimeByExtension($file_ext);
68
	}
69
70
	/**
71
	 * Get MIME type for given extension
72
	 *
73
	 * @param string $ext File extension
74
	 *
75
	 * @return string
76
	 */
77 8
	public function getMimeByExtension($ext)
78
	{
79 8
		$mime_types = [
80 8
			'gif'  => 'image/gif; charset=binary',
81 8
			'png'  => 'image/png; charset=binary',
82 8
			'jpeg' => 'image/jpeg; charset=binary',
83 8
			'jpg'  => 'image/jpeg; charset=binary'
84 8
		];
85
86 8
		return isset($mime_types[$ext]) ? $mime_types[$ext] : '';
87
	}
88
}
89