1 <?php declare(strict_types=1);
3 namespace Cli\Services;
4 use FilesystemIterator;
5 use RecursiveDirectoryIterator;
6 use RecursiveIteratorIterator;
12 public static function move(string $src, string $target): void
14 static::copy($src, $target);
18 public static function copy(string $src, string $target): void
20 if (!file_exists($target)) {
24 /** @var RecursiveDirectoryIterator $files */
25 $files = new RecursiveIteratorIterator(
26 new RecursiveDirectoryIterator($src, FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS),
27 RecursiveIteratorIterator::SELF_FIRST
30 /** @var SplFileInfo $fileinfo */
31 foreach ($files as $fileinfo) {
32 $srcPath = $fileinfo->getRealPath();
33 $subPath = $files->getSubPathName();
34 $destPath = Paths::join($target, $subPath);
36 if ($fileinfo->isDir() && !file_exists($destPath)) {
37 $result = mkdir($destPath);
38 } else if ($fileinfo->isFile()) {
39 $result = copy($srcPath, $destPath);
42 if ($result === false) {
43 throw new \Exception("Failed to copy file or directory from {$srcPath} to {$destPath}");
49 * Delete the contents of the given directory.
50 * Will not delete symlinked folders to ensure that symlinks remain consistent,
51 * but will aim to delete contents of symlinked folders.
53 public static function delete(string $dir): void
55 $files = new RecursiveIteratorIterator(
56 new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS),
57 RecursiveIteratorIterator::CHILD_FIRST
62 /** @var SplFileInfo $fileinfo */
63 foreach ($files as $fileinfo) {
64 $path = $fileinfo->getRealPath();
66 if ($fileinfo->isDir()) {
67 if ($fileinfo->isLink()) {
68 $links .= $fileinfo->getPath() . '::';
69 } else if (!str_contains($links, '::' . $path)) {
70 $result = rmdir($path);
72 } else if ($fileinfo->isFile()) {
73 $result = unlink($path);
76 if ($result === false) {
77 throw new \Exception("Failed to delete file or directory at {$path}");
81 if ($links === '::') {