Passed
Branch scrutinizer (dafd44)
by Wanderson
01:40
created

Directory::removeAllFiles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Win\File;
4
5
use Exception;
6
use Win\Request\Server;
7
8
/**
9
 * Diretório de arquivos
10
 */
11
class Directory {
12
13
	/** @var string */
14
	private $path;
15
16
	/** @param string $path */
17
	public function __construct($path) {
18
		$this->path = str_replace(['///', '//'], ['/', '/'], $path . '/');
19
	}
20
21
	public function __toString() {
22
		return $this->path;
23
	}
24
25
	public function getPath() {
26
		return $this->path;
27
	}
28
29
	public function setPath($path) {
30
		$this->path = $path;
31
	}
32
33
	/**
34
	 * Cria o diretório para salvar a imagem
35
	 * @param string $pathetorio Caminho do novo diretório
36
	 * @param int $chmod permissões deste diretório
37
	 * @return boolean Retorna TRUE caso obtenha algum sucesso
38
	 */
39
	public function create($chmod = 0755) {
40
		if (!file_exists($this->path)) {
41
			$success = @mkdir($this->path, $chmod, (boolean) STREAM_MKDIR_RECURSIVE);
42
			return $success;
43
		}
44
		if (Server::isLocalHost()) {
45
			$success = @chmod($this->path, 0777);
46
			if (!$success) {
47
				throw new Exception('Changing permission (chmod) is not allowed on directory: "' .
48
				$this->path . '". Remove this directory and try again.');
49
			}
50
		}
51
		return false;
52
	}
53
54
	/**
55
	 * Renomeia o diretório
56
	 * @param string $newName Caminho para o novo diretório
57
	 * @return boolean
58
	 */
59
	public function rename($newName) {
60
		if ($this->path != $newName) {
61
			rename($this->path, $newName);
62
			return true;
63
		}
64
		return false;
65
	}
66
67
	/**
68
	 * Exclui o diretório e os arquivos dentro dele
69
	 * @return boolean
70
	 */
71
	public function remove() {
72
		$path = str_replace('//', '/', $this->path);
73
		if (is_dir($path)) {
74
			$this->removeAllFiles();
75
			return rmdir($path);
76
		} else {
77
			return false;
78
		}
79
	}
80
81
	/** Exclui os arquivos deste diretório */
82
	protected function removeAllFiles() {
83
		$path = str_replace('//', '/', $this->path);
84
		$files = array_diff(scandir($path), ['.', '..']);
85
		foreach ($files as $file) {
86
			if (is_dir($path . '/' . $file)) {
87
				$subDirectory = new Directory($path . '/' . $file);
88
				$subDirectory->remove();
89
			} else {
90
				unlink($path . '/' . $file);
91
			}
92
		}
93
	}
94
95
	/** @return string[] */
96
	public function getFiles() {
97
		$path = str_replace('//', '/', $this->path);
98
		$files = array_diff(scandir($path), ['.', '..']);
99
		foreach ($files as $i => $file) {
100
			if (is_dir($path . '/' . $file)) {
101
				unset($files[$i]);
102
			}
103
		}
104
		return $files;
105
	}
106
107
}
108