From d51381f6bdd021264c4c0a97422a2778634a852d Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 2 Feb 2023 05:38:40 +0100 Subject: [PATCH] added Finder::files() & directories() --- src/Utils/Finder.php | 28 ++++++++++++++++++++++++---- tests/Utils/Finder.basic.phpt | 14 ++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/Utils/Finder.php b/src/Utils/Finder.php index 900efe171..d9f8e7171 100644 --- a/src/Utils/Finder.php +++ b/src/Utils/Finder.php @@ -71,19 +71,39 @@ public static function findDirectories(string|array $masks): static } - private function addMask(array $masks, string $type): static + /** + * Finds files matching the specified masks. + */ + public function files(string|array $masks): static + { + return $this->addMask((array) $masks, 'file'); + } + + + /** + * Finds directories matching the specified masks. + */ + public function directories(string|array $masks): static + { + return $this->addMask((array) $masks, 'dir'); + } + + + private function addMask(array $masks, string $mode): static { foreach ($masks as $mask) { $mask = FileSystem::unixSlashes($mask); - if ($mask === '') { + if ($mode === 'dir') { + $mask = rtrim($mask, '/'); + } + if ($mask === '' || ($mode === 'file' && str_ends_with($mask, '/'))) { throw new Nette\InvalidArgumentException("Invalid mask '$mask'"); } if (str_starts_with($mask, '**/')) { $mask = substr($mask, 3); } - $this->find[] = [$mask, $type]; + $this->find[] = [$mask, $mode]; } - return $this; } diff --git a/tests/Utils/Finder.basic.phpt b/tests/Utils/Finder.basic.phpt index 9712cdb4f..95eaffcea 100644 --- a/tests/Utils/Finder.basic.phpt +++ b/tests/Utils/Finder.basic.phpt @@ -54,6 +54,12 @@ test('non-recursive file search', function () { }); +test('non-recursive file search alt', function () { + $finder = (new Finder)->files('file.txt')->in('fixtures.finder'); + Assert::same(['fixtures.finder/file.txt'], export($finder)); +}); + + test('recursive file search', function () { $finder = Finder::findFiles('file.txt')->from('fixtures.finder'); Assert::same([ @@ -117,6 +123,14 @@ test('non-recursive directory search', function () { }); +test('non-recursive directory search alt', function () { + $finder = (new Finder)->directories('subdir*')->in('fixtures.finder'); + Assert::same([ + 'fixtures.finder/subdir', + ], export($finder)); +}); + + test('recursive directory search', function () { $finder = Finder::findDirectories('subdir*')->from('fixtures.finder'); Assert::same([