Completed
Push — master ( a9fbcc...a7b0c2 )
by Wanderson
02:19
created

File::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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
16
	/** @var Directory */
17
	private $directory = null;
18
	protected $uploadPrepared = false;
19
	private $oldName = null;
20
	protected static $maxSize = 10;
21
	protected static $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'csv', 'doc', 'docx', 'odt', 'pdf', 'txt', 'md', 'mp3', 'wav', 'mpeg'];
22
23
	/* Construtor */
24
25
	public function __construct($name = '') {
26
		if (is_file($name)) {
27
			$this->name = pathinfo($name, PATHINFO_BASENAME);
28
			$this->tempName = pathinfo($name, PATHINFO_BASENAME);
29
			$this->extension = pathinfo($name, PATHINFO_EXTENSION);
30
			$directoryPath = (pathinfo($name, PATHINFO_DIRNAME));
31
			$this->directory = new Directory($directoryPath);
32
			$this->size = 1;
33
		}
34
	}
35
36
	/* Metodos de acesso */
37
38
	public function getName() {
39
		return $this->name;
40
	}
41
42
	public function getTempName() {
43
		return $this->tempName;
44
	}
45
46
	public function getExtension() {
47
		if (is_null($this->extension)):
48
			$this->extension = static::getExtensionByName($this->name);
49
		endif;
50
		return $this->extension;
51
	}
52
53
	public function getSize() {
54
		return $this->size;
55
	}
56
57
	public function getDirectory() {
58
		return $this->directory;
59
	}
60
61
	public function getOldName() {
62
		return $this->oldName;
63
	}
64
65
	public function setName($name) {
66
		$this->name = $name;
67
	}
68
69
	public function setTempName($tempName) {
70
		$this->tempName = $tempName;
71
	}
72
73
	/** @param string $directory */
74
	public function setDirectory($directory) {
75
		$this->directory = new Directory($directory);
76
	}
77
78
	public function setOldName($oldName) {
79
		$this->oldName = $oldName;
80
	}
81
82
	public function getFullName() {
83
		return $this->getDirectory() . $this->getName();
84
	}
85
86
	public static function getValidExtensions() {
87
		return static::$validExtensions;
88
	}
89
90
	public function __toString() {
91
		if ($this->getName() != '') {
92
			return $this->getFullName();
93
		} else {
94
			return '';
95
		}
96
	}
97
98
	/* Metodos */
99
100
	/**
101
	 * Recebe o Arquivo temporário
102
	 * @param array $files $_FILES['arquivo']
103
	 * @example $obj->receiveFiles($_FILES['arquivo']);
104
	 */
105
	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...
106
		if ($this->getName() != '') {
107
			$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...
108
		}
109
		if (!empty($files['name'])) {
110
			$this->tempName = $files['tmp_name'];
111
			$this->extension = static::getExtensionByName($files['name']);
112
			$this->size = $files['size'];
113
			$this->uploadPrepared = true;
114
		}
115
	}
116
117
	/**
118
	 * Recebe o Arquivo temporário
119
	 * @param string $fileName $_POST['arquivo']
120
	 * @example $obj->receivePost($_POST['arquivo']);
121
	 */
122
	public function receivePost($fileName) {
123
		if ($this->getName() != '') {
124
			$this->oldName = $this->getFullName();
125
		}
126
		if (!empty($fileName) and file_exists($fileName)) {
127
			$this->tempName = $fileName;
128
			$this->extension = static::getExtensionByName($fileName);
129
			$this->size = -1;
130
			$this->uploadPrepared = true;
131
		}
132
	}
133
134
	/**
135
	 * Realiza o envio para a pasta, reduzindo o tamanho e com um nome aleatório
136
	 * @param string $newName opcional, escolhe o nome que será salvo
137
	 * @return string Retorna algum erro ou NULL
138
	 */
139
	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...
140
141
		if ($this->uploadPrepared) {
142
143
			if (!file_exists($this->tempName)) {
144
				return 'Houve um erro ao enviar o arquivo, verifique se o arquivo não ultrapasse o tamanho máximo permitido. ';
145
			} elseif (!in_array($this->extension, static::$validExtensions)) {
146
				return 'Tipo de arquivo inválido, somente ' . strtoupper(implode('/', static::$validExtensions)) . '.';
147
			} elseif ((!file_exists($this->directory) && !$this->directory->create())) {
148
				return 'O diretorio ' . $this->directory . ' não existe.';
149
			} elseif ($this->size > (static::$maxSize * 1024 * 1024) or $this->size == 0) {
150
				return 'O tamanho do arquivo deve ser entre 0kb e ' . static::$maxSize . 'Mb.';
151
			}
152
153
			/* Gera o nome */
154
			if (empty($newName)) {
155
				$this->name = strtolower(md5(uniqid(time())) . '.' . $this->extension);
156
			} else {
157
				$this->name = strtolower($newName . '.' . $this->extension);
158
			}
159
160
			/* exclui se já existir */
161
			$this->removeOld();
162
			$this->remove();
163
164
			/* Move o arquivo */
165
			if ($this->size === -1) {
166
				$this->move();
167
			} else {
168
				move_uploaded_file($this->getTempName(), $this->getFullName());
169
			}
170
		}
171
		return null;
172
	}
173
174
	/** Retorna true se arquivo existe */
175
	public function exists() {
176
		return ($this->getName() and is_file($this->getFullName()));
177
	}
178
179
	/** Move o arquivo de $temp para $diretorio atual */
180
	public function move() {
181
		if (file_exists($this->getTempName())) {
182
			if ($this->getName() == '') {
183
				$this->setName(md5(uniqid(time())));
184
			}
185
			rename($this->getTempName(), $this->getFullName());
186
			$this->setTempName($this->getFullName());
187
		}
188
	}
189
190
	/** Exclui o arquivo no diretorio */
191
	public function remove() {
192
		if ($this->exists()) {
193
			unlink($this->getFullName());
194
		}
195
	}
196
197
	/** Exclui o arquivo que existia antes de enviar */
198
	public function removeOld() {
199
		if ($this->oldName) {
200
			$oldFile = new File($this->oldName);
201
			$oldFile->remove();
202
		}
203
	}
204
205
	/**
206
	 * Remove diretorio(s) por expressao regular
207
	 * @param string $regExp
208
	 * @return int quantidade de diretorios removidos
209
	 */
210
	public static function removeRegExp($regExp) {
211
		$fileNames = glob($regExp);
212
		foreach ($fileNames as $filename) {
213
			unlink($filename);
214
		}
215
		return count($fileNames);
216
	}
217
218
	/**
219
	 * Retorna a extension pelo nome
220
	 * @param string $name
221
	 * @return string
222
	 */
223
	protected static function getExtensionByName($name) {
224
		$ext = explode('.', $name);
225
		return strtolower(end($ext));
226
	}
227
228
	/**
229
	 * Salva conteudo no arquivo
230
	 * @param string $content
231
	 * @param string $mode
232
	 */
233
	public function write($content = '', $mode = 'a') {
234
		if (!is_null($this->getName())) {
235
			$this->directory->create();
236
			$fp = fopen($this->getFullName(), $mode);
237
			fwrite($fp, $content);
238
			fclose($fp);
239
		}
240
	}
241
242
	/**
243
	 * Retorna o conteudo do arquivo
244
	 * @param string $content
0 ignored issues
show
Bug introduced by
There is no parameter named $content. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
245
	 */
246
	public function read() {
247
		return file_get_contents($this->getFullName());
248
	}
249
250
}
251