Skip to content

Commit 10bb6a1

Browse files
committed
feat: add listFilesRecursively method to File class and corresponding test case
1 parent 331e24b commit 10bb6a1

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

src/Facades/File.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
* @method static int getCreationTime(string $path)
1919
* @method static int getModificationTime(string $path)
2020
* @method static array listFiles(string $path, bool $relativePath = false)
21+
* @method static array listFilesRecursively(string $path, string|null $extension = null)
2122
* @method static void deleteFile(string $path)
2223
* @method static void deleteDirectory(string $path)
2324
*

src/Filesystem/File.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,25 @@ public function listFiles(string $path, bool $relativePath = false): array
7777
}, $this->driver->listFiles($path));
7878
}
7979

80+
public function listFilesRecursively(string $path, string|null $extension = null): array
81+
{
82+
$paths = [];
83+
84+
foreach ($this->listFiles($path) as $file) {
85+
if ($this->driver->isDirectory($file)) {
86+
$paths = array_merge($paths, $this->listFilesRecursively($file, $extension));
87+
88+
continue;
89+
}
90+
91+
if ($this->driver->isFile($file) && ($extension === null || str_ends_with($file, $extension))) {
92+
$paths[] = $file;
93+
}
94+
}
95+
96+
return $paths;
97+
}
98+
8099
public function deleteFile(string $path): void
81100
{
82101
$this->driver->deleteFile($path);

tests/Unit/Filesystem/FileTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,13 @@
100100
$path . DIRECTORY_SEPARATOR . 'FileTest.php',
101101
]);
102102
});
103+
104+
it('list files in a directory recursively', function () {
105+
$path = __DIR__;
106+
107+
$file = new File();
108+
109+
expect($file->listFilesRecursively($path, 'php'))->toBe([
110+
$path . DIRECTORY_SEPARATOR . 'FileTest.php',
111+
]);
112+
});

0 commit comments

Comments
 (0)