Метод hasResults
Метод hasResults класса Finder возвращает
true, если после применения всех фильтров
(name, size, date и других)
остался хотя бы один файл или директория. Если же
результатов нет, метод возвращает false.
Метод не принимает параметров. Его удобно использовать
для проверки существования файлов перед выводом списка.
Синтаксис
public function hasResults(): bool
Пример
Давайте проверим, есть ли в директории файлы
с расширением .php:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Finder;
class FinderController extends AbstractController
{
public function index(): Response
{
$finder = new Finder();
$finder->files()->in('src')->name('*.php');
if ($finder->hasResults()) {
echo 'files found';
} else {
echo 'no files';
}
return new Response();
}
}
?>
Результат выполнения кода:
"files found"
Пример
Давайте проверим наличие файлов, подходящих под слишком строгий фильтр:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Finder;
class FinderController extends AbstractController
{
public function index(): Response
{
$finder = new Finder();
$finder->files()->in('src')->name('*.abcde');
if ($finder->hasResults()) {
echo 'files found';
} else {
echo 'no files';
}
return new Response();
}
}
?>
Результат выполнения кода:
"no files"
Пример
Давайте сохраним список найденных файлов
в массив с помощью метода getIterator,
предварительно проверив наличие результатов:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Finder;
class FinderController extends AbstractController
{
public function index(): Response
{
$finder = new Finder();
$finder->files()->in('src')->name('*.php');
$res = [];
if ($finder->hasResults()) {
foreach ($finder as $file) {
$res[] = $file->getFilename();
}
}
echo implode(', ', $res);
return new Response();
}
}
?>
Результат выполнения кода:
"FinderController.php, Kernel.php"
Смотрите также
-
класс
Finder,
который ищет файлы и директории -
метод
count,
который считает количество найденных элементов -
метод
getIterator,
который возвращает итератор найденных файлов -
метод
name,
который фильтрует файлы по имени