Completed
Push — master ( c7b167...faaa80 )
by Wanderson
02:08
created

File::upload()   D

Complexity

Conditions 9
Paths 9

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 4.909
c 0
b 0
f 0
cc 9
eloc 21
nc 9
nop 1
1
<?php
2
3
namespace Win\File;
4
5
/**
6
 * Arquivos
7
 *
8
 */
9
class File {
10
11
	private $name = null;
12
	private $tempName = null;
13
	private $extension = null;
14
	private $size = 0;
15
	private $directory = null;
16
	protected $uploadPrepared = false;
17
	private $oldName = null;
18
	protected static $maxSize = 10;
19
	protected static $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'csv', 'doc', 'docx', 'odt', 'pdf', 'txt', 'md', 'mp3', 'wav', 'mpeg'];
20
21
	/* Construtor */
22
23
	public function __construct($name = '') {
24
		if (is_file($name)) {
25
			$this->name = pathinfo($name, PATHINFO_BASENAME);
26
			$this->tempName = pathinfo($name, PATHINFO_BASENAME);
27
			$this->extension = pathinfo($name, PATHINFO_EXTENSION);
28
			$directoryPath = (pathinfo($name, PATHINFO_DIRNAME));
29
			$this->directory = new Directory($directoryPath);
30
			$this->size = 1;
31
		}
32
	}
33
34
	/* Metodos de acesso */
35
36
	public function getName() {
37
		return $this->name;
38
	}
39
40
	public function getTempName() {
41
		return $this->tempName;
42
	}
43
44
	public function getExtension() {
45
		if (is_null($this->extension)):
46
			$this->extension = static::getExtensionByName($this->name);
47
		endif;
48
		return $this->extension;
49
	}
50
51
	public function getSize() {
52
		return $this->size;
53
	}
54
55
	public function getDirectory() {
56
		return $this->directory;
57
	}
58
59
	public function getOldName() {
60
		return $this->oldName;
61
	}
62
63
	public function setName($name) {
64
		$this->name = $name;
65
	}
66
67
	public function setTempName($tempName) {
68
		$this->tempName = $tempName;
69
	}
70
71
	/** @param string $directory */
72
	public function setDirectory($directory) {
73
		$this->directory = new Directory($directory);
74
	}
75
76
	public function setOldName($oldName) {
77
		$this->oldName = $oldName;
78
	}
79
80
	public function getFullName() {
81
		return $this->getDirectory() . $this->getName();
82
	}
83
84
	public function __toString() {
85
		if ($this->getName() != '') {
86
			return $this->getFullName();
87
		} else {
88
			return '';
89
		}
90
	}
91
92
	/* Metodos */
93
94
	/**
95
	 * Recebe o Arquivo temporário
96
	 * @param array $files $_FILES['arquivo']
97
	 * @example $obj->receiveFiles($_FILES['arquivo']);
98
	 */
99
	function receiveFiles($files) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
100
		if ($this->getName() != '') {
101
			$this->anterior = $this->getFullName();
0 ignored issues
show
Bug introduced by
The property anterior does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
102
		}
103
		if (!empty($files['name'])) {
104
			$this->tempName = $files['tmp_name'];
105
			$this->extension = static::getExtensionByName($files['name']);
106
			$this->size = $files['size'];
107
			$this->uploadPrepared = true;
108
		}
109
	}
110
111
	/**
112
	 * Recebe o Arquivo temporário
113
	 * @param string $fileName $_POST['arquivo']
114
	 * @example $obj->receivePost($_POST['arquivo']);
115
	 */
116
	public function receivePost($fileName) {
117
		if ($this->getName() != '') {
118
			$this->oldName = $this->getFullName();
119
		}
120
		if (!empty($fileName) and file_exists($fileName)) {
121
			$this->tempName = $fileName;
122
			$this->extension = static::getExtensionByName($fileName);
123
			$this->size = -1;
124
			$this->uploadPrepared = true;
125
		}
126
	}
127
128
	/**
129
	 * Realiza o envio para a pasta, reduzindo o tamanho e com um nome aleatório
130
	 * @param string $newName opcional, escolhe o nome que será salvo
131
	 * @return string Retorna algum erro ou NULL
132
	 */
133
	function upload($newName = '') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
134
135
		if ($this->uploadPrepared) {
136
137
			if (!file_exists($this->tempName)) {
138
				return 'Houve um erro ao enviar o arquivo, verifique se o arquivo não ultrapasse o tamanho máximo permitido. ';
139
			} elseif (!in_array($this->extension, static::$validExtensions)) {
140
				return 'Tipo de arquivo inválido, somente ' . strtoupper(implode('/', static::$validExtensions)) . '.';
141
			} elseif ((!file_exists($this->directory))) {
142
				return 'O diretorio ' . $this->directory . ' não existe.';
143
			} elseif ($this->size > (static::$maxSize * 1024 * 1024) or $this->size == 0) {
144
				return 'O tamanho do arquivo deve ser entre 0kb e ' . static::$maxSize . 'Mb.';
145
			}
146
147
			/* Gera o nome */
148
			if (empty($newName)) {
149
				$this->name = strtolower(md5(uniqid(time())) . '.' . $this->extension);
150
			} else {
151
				$this->name = strtolower($newName . '.' . $this->extension);
152
			}
153
154
			/* exclui se já existir */
155
			$this->removeOld();
156
			$this->remove();
157
158
			/* Move o arquivo */
159
			if ($this->size === -1) {
160
				$this->move();
161
			} else {
162
				move_uploaded_file($this->getTempName(), $this->getFullName());
163
			}
164
		}
165
		return null;
166
	}
167
168
	/** Retorna true se arquivo existe */
169
	public function exists() {
170
		return ($this->getName() and is_file($this->getFullName()));
171
	}
172
173
	/** Move o arquivo de $temp para $diretorio atual */
174
	public function move() {
175
		if ($this->getName() == '') {
176
			$this->setName(md5(uniqid(time())));
177
		}
178
		rename($this->getTempName(), $this->getFullName());
179
		$this->setTempName($this->getFullName());
180
	}
181
182
	/** Exclui o arquivo no diretorio */
183
	public function remove() {
184
		if ($this->exists()) {
185
			unlink($this->getFullName());
186
		}
187
	}
188
189
	/** Exclui o arquivo que existia antes de enviar */
190
	public function removeOld() {
191
		if ($this->oldName) {
192
			$oldFile = new File($this->oldName);
193
			$oldFile->remove();
194
		}
195
	}
196
197
	/**
198
	 * Retorna a extension pelo nome
199
	 * @param string $name
200
	 * @return string
201
	 */
202
	protected static function getExtensionByName($name) {
203
		$ext = explode('.', $name);
204
		return strtolower(end($ext));
205
	}
206
207
}
208