-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFileSystem.php
568 lines (496 loc) · 14.6 KB
/
FileSystem.php
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
<?php declare(strict_types=1);
/**
* This file is part of toolkit/fsutil.
*
* @author https://github.com/inhere
* @link https://github.com/toolkit/fsutil
* @license MIT
*/
namespace Toolkit\FsUtil;
use FilesystemIterator;
use InvalidArgumentException;
use RecursiveCallbackFilterIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Toolkit\FsUtil\Exception\FileNotFoundException;
use Toolkit\FsUtil\Traits\FileSystemFuncTrait;
use Toolkit\Stdlib\OS;
use function array_filter;
use function array_map;
use function count;
use function file_exists;
use function fnmatch;
use function implode;
use function is_array;
use function is_dir;
use function is_file;
use function preg_match;
use function str_ends_with;
use function str_ireplace;
use function str_starts_with;
use function strlen;
use function strpos;
use function substr;
use function trim;
use const DIRECTORY_SEPARATOR;
/**
* Class FileSystem
*
* @package Toolkit\FsUtil
*/
abstract class FileSystem
{
use FileSystemFuncTrait;
/**
* @var string
*/
public const DS = DIRECTORY_SEPARATOR;
/**
* @param string $path
*
* @return bool
*/
public static function isAbsPath(string $path): bool
{
if (!$path) {
return false;
}
if (str_starts_with($path, '/') || // linux/mac
1 === preg_match('#^[a-zA-Z]:[/|\\\].+#i', $path) // windows
) {
return true;
}
return false;
}
/**
* Returns whether the file path is an absolute path.
*
* @from Symfony-filesystem
*
* @param string $file A file path
*
* @return bool
*/
public static function isAbsolutePath(string $file): bool
{
return strspn($file, '/\\', 0, 1) ||
(strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] === ':' && strspn($file, '/\\', 2, 1)) ||
null !== parse_url($file, PHP_URL_SCHEME);
}
/**
* @param string $path
*
* @return bool
*/
public static function isRelative(string $path): bool
{
return !self::isAbsPath($path);
}
/**
* @param string $path
* @param array $patterns eg: ['*.php', '*.html']
*
* @return bool
*/
public static function isExclude(string $path, array $patterns): bool
{
return $patterns && self::isMatch($path, $patterns);
}
/**
* @param string $path
* @param array $patterns eg: ['*.php', '*.html']
*
* @return bool
*/
public static function isInclude(string $path, array $patterns): bool
{
return !$patterns || self::isMatch($path, $patterns);
}
/**
* @param string $path
* @param array $patterns eg: ['*.php', '*.html']
*
* @return bool
*/
public static function isMatch(string $path, array $patterns): bool
{
foreach ($patterns as $pattern) {
if ($pattern === '*' || $pattern === '**/*') {
return true;
}
if ($pattern === $path || fnmatch($pattern, $path)) {
return true;
}
}
return false;
}
/**
* @param string $path
*
* @return string
*/
public static function getAbsPath(string $path): string
{
return self::realpath($path);
}
/**
* Path format. will replace \ to /
*
* @param string $dirName
* @param bool $endWithSlash set end with slash '/'. default true
*
* @return string
*/
public static function pathFormat(string $dirName, bool $endWithSlash = true): string
{
$dirName = (string)str_ireplace('\\', '/', trim($dirName));
if (str_ends_with($dirName, '/')) {
return $endWithSlash ? $dirName : substr($dirName, 0, -1);
}
return $endWithSlash ? $dirName . '/' : $dirName;
}
/**
* Join paths
*
* @param string $basePath
* @param string ...$subPaths
*
* @return string
*/
public static function join(string $basePath, string ...$subPaths): string
{
return self::joinPath($basePath, ...$subPaths);
}
/**
* Join paths
*
* @param string $basePath
* @param string ...$subPaths
*
* @return string
*/
public static function joinPath(string $basePath, string ...$subPaths): string
{
if (str_ends_with($basePath, '/')) {
$basePath = substr($basePath, 0, -1);
}
$subPaths = array_filter(array_map(static function ($path) {
if ($path === '.' || $path === './') {
return '';
}
return trim(str_starts_with($path, './') ? substr($path, 2) : $path, '/\\ ');
}, $subPaths), 'strlen');
if (!$subPaths) {
return $basePath;
}
if (!$basePath) {
return implode(DIRECTORY_SEPARATOR, $subPaths);
}
return $basePath . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $subPaths);
}
/**
* @param string $path
*
* @return string
*/
public static function clearPharPath(string $path): string
{
return self::clearPharMark($path);
}
/**
* @param string $path e.g 'phar://E:/workenv/xxx/yyy/app.phar/web' -> 'E:/workenv/xxx/yyy/web'
*
* @return string
*/
public static function clearPharMark(string $path): string
{
if (str_starts_with($path, 'phar://')) {
$path = substr($path, 7);
if (strpos($path, '.phar') > 0) {
return preg_replace('/\/[\w\.-]+\.phar/', '', $path);
}
}
return $path;
}
/**
* @param string $filepath
*/
public static function assertIsFile(string $filepath): void
{
if (!is_file($filepath)) {
throw new InvalidArgumentException("No such file: $filepath");
}
}
/**
* @param string $dirPath
*/
public static function assertIsDir(string $dirPath): void
{
if (!is_dir($dirPath)) {
throw new InvalidArgumentException("No such directory: $dirPath");
}
}
/**
* @param string $path
*/
public static function assertIsExists(string $path): void
{
if (!file_exists($path)) {
throw new InvalidArgumentException("No such file or directory: $path");
}
}
/**
* @param string $file file or dir path
* @param string $type allow: file, dir, link
*
* @return bool
*/
public static function exists(string $file, string $type = ''): bool
{
return self::isExists($file, $type);
}
/**
* 检查文件/夹/链接是否存在
*
* @param string $file 要检查的目标
* @param string $type allow: file, dir, link
*
* @return bool
*/
public static function isExists(string $file, string $type = ''): bool
{
if (!$type) {
return file_exists($file);
}
$ret = false;
if ($type === 'file') {
$ret = is_file($file);
} elseif ($type === 'dir') {
$ret = is_dir($file);
} elseif ($type === 'link') {
$ret = is_link($file);
}
return $ret;
}
/**
* @param string $file
* @param string|array $ext eg: 'jpg|gif'
*
* @throws FileNotFoundException
*/
public static function check(string $file, array|string $ext = ''): void
{
if (!$file || !file_exists($file)) {
throw new FileNotFoundException("File $file not exists!");
}
if ($ext) {
if (is_array($ext)) {
$ext = implode('|', $ext);
}
if (preg_match("/\.($ext)$/i", $file)) {
throw new InvalidArgumentException("$file extension is not match: $ext");
}
}
}
/**
* Usage:
*
* ```php
* $filter = Dir::getPhpFileFilter();
*
* // $info is instance of \SplFileInfo
* foreach(Dir::getIterator($srcDir, $filter) as $info) {
* // $info->getFilename(); ...
* }
* ```
*
* @param string $srcDir
* @param callable $filter
* @param int $flags
*
* @return RecursiveIteratorIterator
*/
public static function getIterator(
string $srcDir,
callable $filter,
int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO
): RecursiveIteratorIterator
{
if (!$srcDir || !file_exists($srcDir)) {
throw new InvalidArgumentException('Please provide a exists source directory.');
}
$directory = new RecursiveDirectoryIterator($srcDir, $flags);
$filterIterator = new RecursiveCallbackFilterIterator($directory, $filter);
return new RecursiveIteratorIterator($filterIterator);
}
/**
* @param string $path
* @param int $mode
*
* @return bool
*/
public static function chmodDir(string $path, int $mode = 0664): bool
{
if (!is_dir($path)) {
return @chmod($path, $mode);
}
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
if ($file !== '.' && $file !== '..') {
$fullPath = $path . '/' . $file;
if (is_link($fullPath)) {
return false;
}
if (!is_dir($fullPath) && !@chmod($fullPath, $mode)) {
return false;
}
if (!self::chmodDir($fullPath, $mode)) {
return false;
}
}
}
closedir($dh);
return @chmod($path, $mode);
}
/**
* @param string ...$paths directory or file path list
*/
public static function removePaths(string ...$paths): void
{
foreach ($paths as $path) {
self::removePath($path);
}
}
/**
* @param string $path directory or file path
*
* @return void
*/
public static function removePath(string $path): void
{
if (is_dir($path)) {
Dir::delete($path);
} else {
File::delete($path);
}
}
/**
* @param string $dir
*
* @return string
*/
public static function availableSpace(string $dir = '.'): string
{
$base = 1024;
$bytes = disk_free_space($dir);
$suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$class = min((int)log($bytes, $base), count($suffix) - 1);
// echo $bytes . '<br />';
// pow($base, $class)
return sprintf('%1.2f', $bytes / ($base ** $class)) . ' ' . $suffix[$class];
}
/**
* @param string $dir
*
* @return string
*/
public static function countSpace(string $dir = '.'): string
{
$base = 1024;
$bytes = disk_total_space($dir);
$suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$class = min((int)log($bytes, $base), count($suffix) - 1);
// pow($base, $class)
return sprintf('%1.2f', $bytes / ($base ** $class)) . ' ' . $suffix[$class];
}
/**
* 文件或目录权限检查函数
*
* @from web
* @access public
*
* @param string $filepath 文件路径
*
* @return int 返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。
* 返回值在二进制计数法中,四位由高到低分别代表
* 可执行rename()函数权限 |可对文件追加内容权限 |可写入文件权限|可读取文件权限。
*/
public static function pathModeInfo(string $filepath): int
{
/* 如果不存在,则不可读、不可写、不可改 */
if (!file_exists($filepath)) {
return 0;
}
$mark = 0;
if (OS::isWindows()) {
/* 测试文件 */
$test_file = $filepath . '/cf_test.txt';
/* 如果是目录 */
if (is_dir($filepath)) {
/* 检查目录是否可读 */
$dir = @opendir($filepath);
//如果目录打开失败,直接返回目录不可修改、不可写、不可读
if ($dir === false) {
return $mark;
}
//目录可读 001,目录不可读 000
if (@readdir($dir) !== false) {
$mark ^= 1;
}
@closedir($dir);
/* 检查目录是否可写 */
$fp = @fopen($test_file, 'wb');
//如果目录中的文件创建失败,返回不可写。
if ($fp === false) {
return $mark;
}
//目录可写可读 011,目录可写不可读 010
if (@fwrite($fp, 'directory access testing.') !== false) {
$mark ^= 2;
}
@fclose($fp);
@unlink($test_file);
/* 检查目录是否可修改 */
$fp = @fopen($test_file, 'ab+');
if ($fp === false) {
return $mark;
}
if (@fwrite($fp, "modify test.\r\n") !== false) {
$mark ^= 4;
}
@fclose($fp);
/* 检查目录下是否有执行rename()函数的权限 */
if (@rename($test_file, $test_file) !== false) {
$mark ^= 8;
}
@unlink($test_file);
/* 如果是文件 */
} elseif (is_file($filepath)) {
/* 以读方式打开 */
$fp = @fopen($filepath, 'rb');
if ($fp) {
$mark ^= 1; //可读 001
}
@fclose($fp);
/* 试着修改文件 */
$fp = @fopen($filepath, 'ab+');
if ($fp && @fwrite($fp, '') !== false) {
$mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
}
@fclose($fp);
/* 检查目录下是否有执行rename()函数的权限 */
if (@rename($test_file, $test_file) !== false) {
$mark ^= 8;
}
}
} else {
if (@is_readable($filepath)) {
$mark ^= 1;
}
if (@is_writable($filepath)) {
$mark ^= 14;
}
}
return $mark;
}
}