Completed
Push — master ( dd5c07...b4647f )
by Wanderson
02:12
created

File::read()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 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 function __toString() {
87
		if ($this->getName() != '') {
88
			return $this->getFullName();
89
		} else {
90
			return '';
91
		}
92
	}
93
94
	/* Metodos */
95
96
	/**
97
	 * Recebe o Arquivo temporário
98
	 * @param array $files $_FILES['arquivo']
99
	 * @example $obj->receiveFiles($_FILES['arquivo']);
100
	 */
101
	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...
102
		if ($this->getName() != '') {
103
			$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...
104
		}
105
		if (!empty($files['name'])) {
106
			$this->tempName = $files['tmp_name'];
107
			$this->extension = static::getExtensionByName($files['name']);
108
			$this->size = $files['size'];
109
			$this->uploadPrepared = true;
110
		}
111
	}
112
113
	/**
114
	 * Recebe o Arquivo temporário
115
	 * @param string $fileName $_POST['arquivo']
116
	 * @example $obj->receivePost($_POST['arquivo']);
117
	 */
118
	public function receivePost($fileName) {
119
		if ($this->getName() != '') {
120
			$this->oldName = $this->getFullName();
121
		}
122
		if (!empty($fileName) and file_exists($fileName)) {
123
			$this->tempName = $fileName;
124
			$this->extension = static::getExtensionByName($fileName);
125
			$this->size = -1;
126
			$this->uploadPrepared = true;
127
		}
128
	}
129
130
	/**
131
	 * Realiza o envio para a pasta, reduzindo o tamanho e com um nome aleatório
132
	 * @param string $newName opcional, escolhe o nome que será salvo
133
	 * @return string Retorna algum erro ou NULL
134
	 */
135
	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...
136
137
		if ($this->uploadPrepared) {
138
139
			if (!file_exists($this->tempName)) {
140
				return 'Houve um erro ao enviar o arquivo, verifique se o arquivo não ultrapasse o tamanho máximo permitido. ';
141
			} elseif (!in_array($this->extension, static::$validExtensions)) {
142
				return 'Tipo de arquivo inválido, somente ' . strtoupper(implode('/', static::$validExtensions)) . '.';
143
			} elseif ((!file_exists($this->directory) && !$this->directory->create(0777))) {
144
				return 'O diretorio ' . $this->directory . ' não existe.';
145
			} elseif ($this->size > (static::$maxSize * 1024 * 1024) or $this->size == 0) {
146
				return 'O tamanho do arquivo deve ser entre 0kb e ' . static::$maxSize . 'Mb.';
147
			}
148
149
			/* Gera o nome */
150
			if (empty($newName)) {
151
				$this->name = strtolower(md5(uniqid(time())) . '.' . $this->extension);
152
			} else {
153
				$this->name = strtolower($newName . '.' . $this->extension);
154
			}
155
156
			/* exclui se já existir */
157
			$this->removeOld();
158
			$this->remove();
159
160
			/* Move o arquivo */
161
			if ($this->size === -1) {
162
				$this->move();
163
			} else {
164
				move_uploaded_file($this->getTempName(), $this->getFullName());
165
			}
166
		}
167
		return null;
168
	}
169
170
	/** Retorna true se arquivo existe */
171
	public function exists() {
172
		return ($this->getName() and is_file($this->getFullName()));
173
	}
174
175
	/** Move o arquivo de $temp para $diretorio atual */
176
	public function move() {
177
		if (file_exists($this->getTempName())) {
178
			if ($this->getName() == '') {
179
				$this->setName(md5(uniqid(time())));
180
			}
181
			rename($this->getTempName(), $this->getFullName());
182
			$this->setTempName($this->getFullName());
183
		}
184
	}
185
186
	/** Exclui o arquivo no diretorio */
187
	public function remove() {
188
		if ($this->exists()) {
189
			unlink($this->getFullName());
190
		}
191
	}
192
193
	/** Exclui o arquivo que existia antes de enviar */
194
	public function removeOld() {
195
		if ($this->oldName) {
196
			$oldFile = new File($this->oldName);
197
			$oldFile->remove();
198
		}
199
	}
200
201
	/**
202
	 * Remove diretorio(s) por expressao regular
203
	 * @param string $regExp
204
	 * @return int quantidade de diretorios removidos
205
	 */
206
	public static function removeRegExp($regExp) {
207
		$fileNames = glob($regExp);
208
		foreach ($fileNames as $filename) {
209
			unlink($filename);
210
		}
211
		return count($fileNames);
212
	}
213
214
	/**
215
	 * Retorna a extension pelo nome
216
	 * @param string $name
217
	 * @return string
218
	 */
219
	protected static function getExtensionByName($name) {
220
		$ext = explode('.', $name);
221
		return strtolower(end($ext));
222
	}
223
224
	/**
225
	 * Salva conteudo no arquivo
226
	 * @param string $content
227
	 * @param string $mode
228
	 */
229
	public function write($content = '', $mode = 'a') {
230
		if (!is_null($this->getName())) {
231
			$this->directory->create(0777);
232
			$fp = fopen($this->getFullName(), $mode);
233
			fwrite($fp, $content);
234
			fclose($fp);
235
		}
236
	}
237
238
	/**
239
	 * Retorna o conteudo do arquivo
240
	 * @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...
241
	 */
242
	public function read() {
243
		return file_get_contents($this->getFullName());
244
	}
245
246
}
247