Passed
Pull Request — master (#22)
by Wanderson
02:51
created

Filesystem::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Win\Services;
4
5
use Exception;
6
7
class Filesystem
8
{
9
	const DS = DIRECTORY_SEPARATOR;
10
11
	/** @var string[]|null */
12
	protected $tempFile;
13
14
	/**
15
	 * Retorna array com arquivos e diretórios
16
	 * @param string $path
17
	 * @return string[]
18
	 */
19
	public function children($path = '')
20
	{
21
		return array_diff((array) scandir(BASE_PATH . "/$path"), ['..', '.']);
22
	}
23
24
	/**
25
	 * Retorna total de items
26
	 * @param string $path
27
	 * @return int
28
	 */
29
	public function count($path)
30
	{
31
		return count($this->children($path));
32
	}
33
34
	/**
35
	 * Cria o diretório
36
	 * @param string $folderPath
37
	 * @param int $chmod Permissão (base 8)
38
	 */
39
	public function create($folderPath, $chmod = 0755)
40
	{
41
		$path = BASE_PATH . "/$folderPath";
42
		if (!is_dir($path)) {
43
			$mask = umask(0);
44
			if (!@mkdir($path, $chmod, true)) {
45
				throw new Exception("O diretório '{$folderPath}' não existe ou não possui permissão.");
46
			}
47
			umask($mask);
48
		}
49
	}
50
51
	/**
52
	 * Renomeia o arquivo
53
	 * @param string $filePath
54
	 * @param string $newFilePath
55
	 * @return bool
56
	 */
57
	public function rename($filePath, $newFilePath)
58
	{
59
		return rename(BASE_PATH . "/$filePath", BASE_PATH . "/$newFilePath");
60
	}
61
62
	/**
63
	 * Move o arquivo
64
	 * @param string $filePath
65
	 * @param string $newFolder
66
	 */
67
	public function move($filePath, $newFolder)
68
	{
69
		return rename(BASE_PATH . "/$filePath", BASE_PATH . "/$newFolder");
70
	}
71
72
	/**
73
	 * Exclui o arquivo/diretório
74
	 * @param string $path Caminho do arquivo/diretório
75
	 * @return bool
76
	 */
77
	public function delete($path)
78
	{
79
		$fullPath = BASE_PATH . "/$path";
80
		if (is_dir($fullPath) && !is_link($fullPath)) {
81
			foreach ($this->children($path) as $child) {
82
				$this->delete("$path/$child");
83
			}
84
			rmdir($fullPath);
85
		} elseif (is_file($fullPath)) {
86
			unlink($fullPath);
87
		}
88
	}
89
90
	/**
91
	 * Salva o conteúdo no arquivo
92
	 * @param string $content
93
	 * @param string $mode
94
	 * @return bool
95
	 */
96
	public function write($filePath, $content, $mode = 'w')
97
	{
98
		$dir = pathinfo($filePath, PATHINFO_DIRNAME);
99
		$file = pathinfo($filePath, PATHINFO_BASENAME);
100
		$return = false;
101
102
		if ($dir) {
103
			$this->create($dir, 0777);
104
			$fp = fopen(BASE_PATH . "/{$dir}/{$file}", $mode);
105
			if (false !== $fp) {
106
				fwrite($fp, $content);
107
				$return = fclose($fp);
108
			}
109
		}
110
111
		return $return;
112
	}
113
114
	/**
115
	 * Retorna o conteúdo do arquivo
116
	 * @return string|false
117
	 */
118
	public function read($filePath)
119
	{
120
		if (!$this->exists($filePath)) {
121
			return false;
122
		}
123
		return file_get_contents(BASE_PATH . "/$filePath");
124
	}
125
126
	/**
127
	 * Retorna TRUE se o arquivo existe
128
	 * @param string $filePath
129
	 * @return bool
130
	 */
131
	public function exists($filePath)
132
	{
133
		$filePath = BASE_PATH . "/$filePath";
134
135
		return is_file($filePath) or is_dir($filePath);
136
	}
137
138
	/**
139
	 * Prepara o upload
140
	 * @param string[] $tempFile
141
	 * @param string[] $extensions
142
	 */
143
	public function receiveFile(
144
		$tempFileFile,
145
		$extensions = ['csv', 'doc', 'docx', 'gif', 'jpeg', 'jpg', 'md', 'mp3', 'mp4', 'mpeg', 'pdf', 'png', 'svg', 'txt', 'wav', 'xls', 'xlsx', 'zip',]
146
	) {
147
		if (isset($tempFileFile['name'])) {
148
			$extension = pathinfo($tempFileFile['name'])['extension'];
149
			if (!in_array($extension, $extensions)) {
150
				throw new \Exception("A extensão {$extension} não é permitida.");
151
			}
152
		}
153
154
		if (is_null($tempFileFile) || $tempFileFile['error']) {
155
			throw new \Exception("Erro ao receber o arquivo.");
156
		}
157
158
		$this->tempFile = $tempFileFile;
159
	}
160
161
	/**
162
	 * Faz o upload para o diretório final
163
	 * @param string $directoryPath
164
	 * @param string $name
165
	 * @return string
166
	 */
167
	public function upload($directoryPath, $name = null)
168
	{
169
		if (!is_null($this->tempFile)) {
170
			$name = $this->generateName($name);
171
			$this->create($directoryPath);
172
			\move_uploaded_file($this->tempFile['tmp_name'], "$directoryPath/$name");
173
174
			return $name;
175
		} else {
176
			throw new \Exception("Erro ao enviar o arquivo.");
177
		}
178
	}
179
180
	/**
181
	 * Gera um novo nome, mantendo a extensão
182
	 * @param string $name
183
	 */
184
	protected function generateName($name)
185
	{
186
		$info = pathinfo($this->tempFile['name']);
187
		return ($name ?? md5('Y-m-d H:i:s') . $this->tempFile['name']) . '.' . $info['extension'];
188
	}
189
}
190