Метод path класса Finder
Метод path класса Finder
позволяет отфильтровать файлы и директории
по их пути. Первым параметром передаётся
строка пути или регулярное выражение.
Второй параметр задаёт тип сравнения:
'equal', 'contains',
'starts_with',
'ends_with',
'not_equal',
'not_contains',
'not_starts_with' или
'not_ends_with'.
Метод возвращает сам объект Finder,
что позволяет строить цепочки вызовов.
Синтаксис
public function path(string|array $patterns, string $type = 'equal'): static
Пример
Давайте найдём все файлы, путь которых начинается
с 'abcde':
<?php
namespace AppService;
use SymfonyComponentFinderFinder;
class FileService
{
public function findFiles(): array
{
$finder = new Finder();
$finder->files()->in('src')->path('abcde', 'starts_with');
$res = [];
foreach ($finder as $file) {
$res[] = $file->getRelativePathname();
}
return $res;
}
}
?>
Результат выполнения кода:
["abcde_file.php", "abcde_dir/abcde_article.php"]
Пример
Давайте отфильтруем файлы, путь которых содержит
подстроку 'article':
<?php
namespace AppService;
use SymfonyComponentFinderFinder;
class ArticleService
{
public function findArticles(): array
{
$finder = new Finder();
$finder->files()->in('templates')->path('article', 'contains');
$res = [];
foreach ($finder as $file) {
$res[] = $file->getRelativePathname();
}
return $res;
}
}
?>
Результат выполнения кода:
["article/index.html.twig", "article/show.html.twig"]
Пример
Давайте исключим файлы, путь которых заканчивается
на '.html.twig', используя регулярное выражение
с флагом 'not_ends_with':
<?php
namespace AppService;
use SymfonyComponentFinderFinder;
class TemplateService
{
public function findPhpFiles(): array
{
$finder = new Finder();
$finder->files()->in('templates')->path('/\.html\.twig$/', 'not_ends_with');
$res = [];
foreach ($finder as $file) {
$res[] = $file->getRelativePathname();
}
return $res;
}
}
?>
Результат выполнения кода:
[]