-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilesystem.php
More file actions
648 lines (552 loc) · 16.2 KB
/
Copy pathFilesystem.php
File metadata and controls
648 lines (552 loc) · 16.2 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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
<?php
/**
* Filesystem class file.
*
* phpcs:disable WordPressVIPMinimum.Functions.RestrictedFunctions
*
* @package Mantle
*/
namespace Mantle\Filesystem;
use ErrorException;
use FilesystemIterator;
use Mantle\Support\Str;
use Mantle\Support\Traits\Macroable;
use RuntimeException;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Mime\MimeTypes;
/**
* Filesystem Interface
*/
class Filesystem {
use Macroable;
/**
* Determine if a file or directory exists.
*
* @param string $path
*/
public function exists( string $path ): bool {
return file_exists( $path );
}
/**
* Determine if a file or directory is missing.
*
* @param string $path
*/
public function missing( string $path ): bool {
return ! $this->exists( $path );
}
/**
* Get the contents of a file.
*
* @param string $path
* @param bool $lock
*
* @throws File_Not_Found_Exception Thrown on missing file.
*/
public function get( string $path, bool $lock = false ): string {
if ( $this->is_file( $path ) ) {
return $lock ? (string) $this->shared_get( $path ) : (string) file_get_contents( $path ); // phpcs:ignore WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown
}
throw new File_Not_Found_Exception( "File does not exist at path {$path}." );
}
/**
* Get contents of a file with shared access.
*
* @param string $path
* @return string
*/
public function shared_get( string $path ): string|false {
$contents = '';
$handle = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
if ( $handle ) {
try {
if ( flock( $handle, LOCK_SH ) ) {
clearstatcache( true, $path );
$contents = fread( $handle, max( 1, (int) $this->size( $path ) ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread
flock( $handle, LOCK_UN );
}
} finally {
fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
}
}
return $contents;
}
/**
* Get the returned value of a file.
*
* @param string $path
* @param array<string, mixed> $data
* @return mixed
*
* @throws File_Not_Found_Exception Thrown on missing file.
*/
public function get_require( string $path, array $data = [] ) {
if ( $this->is_file( $path ) ) {
$__path = $path;
$__data = $data;
return ( static function () use ( $__path, $__data ) {
global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;
extract( $__data, EXTR_SKIP ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract, WordPress.PHP.DiscouragedPHPFunctions.extract_extract
return require $__path; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
} )();
}
throw new File_Not_Found_Exception( "File does not exist at path {$path}." );
}
/**
* Require the given file once.
*
* @param string $path
* @param array $data
* @return mixed
*
* @throws File_Not_Found_Exception Thrown on missing file.
*/
public function require_once( string $path, array $data = [] ) {
if ( $this->is_file( $path ) ) {
$__path = $path;
$__data = $data;
return ( static function () use ( $__path, $__data ) {
extract( $__data, EXTR_SKIP ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract, WordPress.PHP.DiscouragedPHPFunctions.extract_extract
return require_once $__path; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
} )();
}
throw new File_Not_Found_Exception( "File does not exist at path {$path}." );
}
/**
* Get the MD5 hash of the file at the given path.
*
* @param string $path
*/
public function hash( string $path ): string|false {
return md5_file( $path );
}
/**
* Write the contents of a file.
*
* @param string $path
* @param string $contents
* @param bool $lock
*/
public function put( string $path, string $contents, bool $lock = false ): int|false {
return file_put_contents( $path, $contents, $lock ? LOCK_EX : 0 );
}
/**
* Write the contents of a file as JSON.
*
* @param string $path
* @param mixed $data
* @param int $options
*/
public function put_json( string $path, mixed $data, int $options = 0 ): int|false {
$contents = json_encode( $data, $options ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
if ( false === $contents ) {
return false;
}
return $this->put( $path, $contents );
}
/**
* Write the contents of a file, replacing it atomically if it already exists.
*
* @param string $path
* @param string $content
*/
public function replace( string $path, string $content ): void {
// If the path already exists and is a symlink, get the real path...
clearstatcache( true, $path );
$path = realpath( $path ) ?: $path;
$temp_path = tempnam( dirname( $path ), basename( $path ) );
// Fix permissions of tempPath because `tempnam()` creates it with permissions set to 0600...
chmod( $temp_path, 0777 - umask() );
file_put_contents( $temp_path, $content );
rename( $temp_path, $path );
}
/**
* Prepend to a file.
*
* @param string $path
* @param string $data
* @return int
*/
public function prepend( $path, string $data ): int|false {
if ( $this->exists( $path ) ) {
return $this->put( $path, $data . $this->get( $path ) );
}
return $this->put( $path, $data );
}
/**
* Append to a file.
*
* @param string $path
* @param string $data
* @return int
*/
public function append( $path, $data ): int|false {
return file_put_contents( $path, $data, FILE_APPEND );
}
/**
* Get or set UNIX mode of a file or directory.
*
* @param string $path
* @param int|null $mode
*/
public function chmod( string $path, ?int $mode = null ): bool|string {
if ( $mode ) {
return chmod( $path, $mode );
}
return substr( sprintf( '%o', fileperms( $path ) ), -4 );
}
/**
* Delete the file at a given path.
*
* @param string ...$paths
*/
public function delete( string ...$paths ): bool {
$success = true;
foreach ( $paths as $path ) {
try {
if ( @unlink( $path ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Generic.PHP.NoSilencedErrors.Forbidden
clearstatcache( false, $path );
} else {
$success = false;
}
} catch ( ErrorException ) {
$success = false;
}
}
return $success;
}
/**
* Move a file to a new location.
*
* @param string $path
* @param string $target
*/
public function move( string $path, string $target ): bool {
return rename( $path, $target );
}
/**
* Copy a file to a new location.
*
* @param string $path
* @param string $target
*/
public function copy( string $path, string $target ): bool {
return copy( $path, $target );
}
/**
* Create a symlink to the target file or directory. On Windows, a hard link is created if the target is a file.
*
* @param string $target
* @param string $link
*/
public function link( string $target, string $link ): void {
$mode = $this->is_directory( $target ) ? 'J' : 'H';
exec( "mklink /{$mode} " . escapeshellarg( $link ) . ' ' . escapeshellarg( $target ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec
}
/**
* Extract the file name from a file path.
*
* @param string $path
*/
public function name( string $path ): string {
return pathinfo( $path, PATHINFO_FILENAME );
}
/**
* Extract the trailing name component from a file path.
*
* @param string $path
*/
public function basename( string $path ): string {
return pathinfo( $path, PATHINFO_BASENAME );
}
/**
* Extract the parent directory from a file path.
*
* @param string $path
*/
public function dirname( string $path ): string {
return pathinfo( $path, PATHINFO_DIRNAME );
}
/**
* Extract the file extension from a file path.
*
* @param string $path
*/
public function extension( string $path ): string {
return pathinfo( $path, PATHINFO_EXTENSION );
}
/**
* Guess the file extension from the mime-type of a given file.
*
* @param string $path
*
* @throws RuntimeException Thrown on missing extension.
*/
public function guess_extension( string $path ): ?string {
if ( ! class_exists( MimeTypes::class ) ) {
throw new RuntimeException(
'To enable support for guessing extensions, please install the symfony/mime package.'
);
}
return ( new MimeTypes() )->getExtensions( (string) $this->mime_type( $path ) )[0] ?? null;
}
/**
* Guess the class name for a file path.
*
* @param string $path File path.
*/
public function guess_class_name( string $path ): ?string {
$name = $this->name( $path );
if ( Str::starts_with( $name, [ 'class-', 'trait-', 'interface-' ] ) ) {
$name = (string) preg_replace( '/^(\w*-)/', '', $name, 1 );
return Str::studly_underscore( $name );
}
return $name;
}
/**
* Get the file type of a given file.
*
* @param string $path
*/
public function type( string $path ): string|false {
return filetype( $path );
}
/**
* Get the mime-type of a given file.
*
* @param string $path
*/
public function mime_type( string $path ): string|false {
$finfo = finfo_open( FILEINFO_MIME_TYPE );
if ( ! $finfo ) {
return false;
}
return finfo_file( $finfo, $path );
}
/**
* Get the file size of a given file.
*
* @param string $path
*/
public function size( string $path ): int|false {
return filesize( $path );
}
/**
* Get the file's last modification time.
*
* @param string $path
*/
public function last_modified( string $path ): int|false {
return filemtime( $path );
}
/**
* Determine if the given path is a directory.
*
* @param string $directory
*/
public function is_directory( string $directory ): bool {
return is_dir( $directory );
}
/**
* Determine if the given path is readable.
*
* @param string $path
*/
public function is_readable( string $path ): bool {
return is_readable( $path );
}
/**
* Determine if the given path is writable.
*
* @param string $path
*/
public function is_writable( string $path ): bool {
return is_writable( $path );
}
/**
* Determine if the given path is a file.
*
* @param string $file
*/
public function is_file( string $file ): bool {
return is_file( $file );
}
/**
* Find path names matching a given pattern.
*
* @param string $pattern
* @param int $flags
* @return array<string>
*/
public function glob( string $pattern, int $flags = 0 ): array {
return glob( $pattern, $flags ) ?: [];
}
/**
* Get an array of all files in a directory.
*
* @param string $directory
* @param bool $hidden
* @return \Symfony\Component\Finder\SplFileInfo[]
*/
public function files( string|array $directory, $hidden = false ): array {
return iterator_to_array(
Finder::create()->files()->ignoreDotFiles( ! $hidden )->in( $directory )->depth( 0 )->sortByName(),
false
);
}
/**
* Get all of the files from the given directory (recursive).
*
* @param string $directory
* @param bool $hidden
* @return \Symfony\Component\Finder\SplFileInfo[]
*/
public function all_files( string|array $directory, $hidden = false ): array {
return iterator_to_array(
Finder::create()->files()->ignoreDotFiles( ! $hidden )->in( $directory )->sortByName(),
false
);
}
/**
* Get all of the directories within a given directory.
*
* @param string|string[] $directory
* @return string[]
*/
public function directories( string|array $directory ): array {
$directories = [];
foreach ( Finder::create()->in( $directory )->directories()->depth( 0 )->sortByName() as $dir ) {
$directories[] = $dir->getPathname();
}
return $directories;
}
/**
* Ensure a directory exists.
*
* @param string $path
* @param int $mode
* @param bool $recursive
*/
public function ensure_directory_exists( string $path, int $mode = 0755, bool $recursive = true ): bool {
if ( ! $this->is_directory( $path ) ) {
return $this->make_directory( $path, $mode, $recursive );
}
return true;
}
/**
* Create a directory.
*
* @param string $path
* @param int $mode
* @param bool $recursive
*/
public function make_directory( string $path, int $mode = 0755, bool $recursive = false ): bool {
return mkdir( $path, $mode, $recursive );
}
/**
* Move a directory.
*
* @param string $from
* @param string $to
* @param bool $overwrite
*/
public function move_directory( string $from, string $to, bool $overwrite = false ): bool {
if ( $overwrite && $this->is_directory( $to ) && ! $this->delete_directory( $to ) ) {
return false;
}
return @rename( $from, $to ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Generic.PHP.NoSilencedErrors.Forbidden
}
/**
* Copy a directory from one location to another.
*
* @param string $directory
* @param string $destination
* @param int|null $options
*/
public function copy_directory( string $directory, string $destination, ?int $options = null ): bool {
if ( ! $this->is_directory( $directory ) ) {
return false;
}
$options = $options ?: FilesystemIterator::SKIP_DOTS;
// If the destination directory does not actually exist, we will go ahead and
// create it recursively, which just gets the destination prepared to copy
// the files over. Once we make the directory we'll proceed the copying.
$this->ensure_directory_exists( $destination, 0777 );
$items = new FilesystemIterator( $directory, $options );
foreach ( $items as $item ) {
assert( $item instanceof \SplFileInfo );
// As we spin through items, we will check to see if the current file is actually
// a directory or a file. When it is actually a directory we will need to call
// back into this function recursively to keep copying these nested folders.
$target = $destination . '/' . $item->getBasename();
if ( $item->isDir() ) {
$path = $item->getPathname();
if ( ! $this->copy_directory( $path, $target, $options ) ) {
return false;
}
} elseif ( ! $this->copy( $item->getPathname(), $target ) ) {
// If the current items is just a regular file, we will just copy this to the new
// location and keep looping. If for some reason the copy fails we'll bail out
// and return false, so the developer is aware that the copy process failed.
return false;
}
}
return true;
}
/**
* Recursively delete a directory.
*
* The directory itself may be optionally preserved.
*
* @param string $directory
* @param bool $preserve
*/
public function delete_directory( string $directory, bool $preserve = false ): bool {
if ( ! $this->is_directory( $directory ) ) {
return false;
}
$items = new FilesystemIterator( $directory );
foreach ( $items as $item ) {
assert( $item instanceof \SplFileInfo );
// If the item is a directory, we can just recurse into the function and
// delete that sub-directory otherwise we'll just delete the file and
// keep iterating through each file until the directory is cleaned.
if ( $item->isDir() && ! $item->isLink() ) {
$this->delete_directory( $item->getPathname() );
} else {
// If the item is just a file, we can go ahead and delete it since we're
// just looping through and waxing all of the files in this directory
// and calling directories recursively, so we delete the real path.
$this->delete( $item->getPathname() );
}
}
unset( $items );
if ( ! $preserve ) {
@rmdir( $directory ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Generic.PHP.NoSilencedErrors.Forbidden
}
return true;
}
/**
* Remove all of the directories within a given directory.
*
* @param string|string[] $directory
*/
public function delete_directories( string|array $directory ): bool {
$all_directories = $this->directories( $directory );
if ( ! empty( $all_directories ) ) {
foreach ( $all_directories as $all_directory ) {
$this->delete_directory( $all_directory );
}
return true;
}
return false;
}
/**
* Empty the specified directory of all files and folders.
*
* @param string $directory
*/
public function clean_directory( string $directory ): bool {
return $this->delete_directory( $directory, true );
}
}