FileSystem.php
7.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Utils;
use Nette;
/**
* File system tool.
*/
final class FileSystem
{
use Nette\StaticClass;
/**
* Creates a directory if it does not exist, including parent directories.
* @throws Nette\IOException on error occurred
*/
public static function createDir(string $dir, int $mode = 0777): void
{
if (!is_dir($dir) && !@mkdir($dir, $mode, true) && !is_dir($dir)) { // @ - dir may already exist
throw new Nette\IOException(sprintf(
"Unable to create directory '%s' with mode %s. %s",
self::normalizePath($dir),
decoct($mode),
Helpers::getLastError()
));
}
}
/**
* Copies a file or an entire directory. Overwrites existing files and directories by default.
* @throws Nette\IOException on error occurred
* @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists
*/
public static function copy(string $origin, string $target, bool $overwrite = true): void
{
if (stream_is_local($origin) && !file_exists($origin)) {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin)));
} elseif (!$overwrite && file_exists($target)) {
throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target)));
} elseif (is_dir($origin)) {
static::createDir($target);
foreach (new \FilesystemIterator($target) as $item) {
static::delete($item->getPathname());
}
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) {
if ($item->isDir()) {
static::createDir($target . '/' . $iterator->getSubPathName());
} else {
static::copy($item->getPathname(), $target . '/' . $iterator->getSubPathName());
}
}
} else {
static::createDir(dirname($target));
if (
($s = @fopen($origin, 'rb'))
&& ($d = @fopen($target, 'wb'))
&& @stream_copy_to_stream($s, $d) === false
) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to copy file '%s' to '%s'. %s",
self::normalizePath($origin),
self::normalizePath($target),
Helpers::getLastError()
));
}
}
}
/**
* Deletes a file or an entire directory if exists. If the directory is not empty, it deletes its contents first.
* @throws Nette\IOException on error occurred
*/
public static function delete(string $path): void
{
if (is_file($path) || is_link($path)) {
$func = DIRECTORY_SEPARATOR === '\\' && is_dir($path) ? 'rmdir' : 'unlink';
if (!@$func($path)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to delete '%s'. %s",
self::normalizePath($path),
Helpers::getLastError()
));
}
} elseif (is_dir($path)) {
foreach (new \FilesystemIterator($path) as $item) {
static::delete($item->getPathname());
}
if (!@rmdir($path)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to delete directory '%s'. %s",
self::normalizePath($path),
Helpers::getLastError()
));
}
}
}
/**
* Renames or moves a file or a directory. Overwrites existing files and directories by default.
* @throws Nette\IOException on error occurred
* @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists
*/
public static function rename(string $origin, string $target, bool $overwrite = true): void
{
if (!$overwrite && file_exists($target)) {
throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target)));
} elseif (!file_exists($origin)) {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin)));
} else {
static::createDir(dirname($target));
if (realpath($origin) !== realpath($target)) {
static::delete($target);
}
if (!@rename($origin, $target)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to rename file or directory '%s' to '%s'. %s",
self::normalizePath($origin),
self::normalizePath($target),
Helpers::getLastError()
));
}
}
}
/**
* Reads the content of a file.
* @throws Nette\IOException on error occurred
*/
public static function read(string $file): string
{
$content = @file_get_contents($file); // @ is escalated to exception
if ($content === false) {
throw new Nette\IOException(sprintf(
"Unable to read file '%s'. %s",
self::normalizePath($file),
Helpers::getLastError()
));
}
return $content;
}
/**
* Writes the string to a file.
* @throws Nette\IOException on error occurred
*/
public static function write(string $file, string $content, ?int $mode = 0666): void
{
static::createDir(dirname($file));
if (@file_put_contents($file, $content) === false) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to write file '%s'. %s",
self::normalizePath($file),
Helpers::getLastError()
));
}
if ($mode !== null && !@chmod($file, $mode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod file '%s' to mode %s. %s",
self::normalizePath($file),
decoct($mode),
Helpers::getLastError()
));
}
}
/**
* Sets file permissions to `$fileMode` or directory permissions to `$dirMode`.
* Recursively traverses and sets permissions on the entire contents of the directory as well.
* @throws Nette\IOException on error occurred
*/
public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666): void
{
if (is_file($path)) {
if (!@chmod($path, $fileMode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod file '%s' to mode %s. %s",
self::normalizePath($path),
decoct($fileMode),
Helpers::getLastError()
));
}
} elseif (is_dir($path)) {
foreach (new \FilesystemIterator($path) as $item) {
static::makeWritable($item->getPathname(), $dirMode, $fileMode);
}
if (!@chmod($path, $dirMode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod directory '%s' to mode %s. %s",
self::normalizePath($path),
decoct($dirMode),
Helpers::getLastError()
));
}
} else {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($path)));
}
}
/**
* Determines if the path is absolute.
*/
public static function isAbsolute(string $path): bool
{
return (bool) preg_match('#([a-z]:)?[/\\\\]|[a-z][a-z0-9+.-]*://#Ai', $path);
}
/**
* Normalizes `..` and `.` and directory separators in path.
*/
public static function normalizePath(string $path): string
{
$parts = $path === '' ? [] : preg_split('~[/\\\\]+~', $path);
$res = [];
foreach ($parts as $part) {
if ($part === '..' && $res && end($res) !== '..' && end($res) !== '') {
array_pop($res);
} elseif ($part !== '.') {
$res[] = $part;
}
}
return $res === ['']
? DIRECTORY_SEPARATOR
: implode(DIRECTORY_SEPARATOR, $res);
}
/**
* Joins all segments of the path and normalizes the result.
*/
public static function joinPaths(string ...$paths): string
{
return self::normalizePath(implode('/', $paths));
}
}