Метод has класса InputBag
Метод has класса InputBag проверяет,
присутствует ли указанный ключ в контейнере
параметров запроса. Первым параметром передаётся
имя ключа. Метод возвращает true, если ключ
существует, и false в противном случае.
Класс InputBag используется для хранения
GET и POST параметров запроса.
Синтаксис
public function has(string $key): bool
Пример
Давайте проверим наличие параметра user в
GET-запросе:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
if ($bag->has('user')) {
return new Response('user found');
}
return new Response('user not found');
}
}
?>
Результат выполнения кода для адреса
/article?user=abcde:
user found
Результат выполнения кода для адреса
/article:
user not found
Пример
Давайте проверим наличие параметра text в
POST-запросе:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->request;
if ($bag->has('text')) {
return new Response('text found');
}
return new Response('text not found');
}
}
?>
Результат выполнения кода для POST-запроса
с полем text:
text found
Результат выполнения кода для POST-запроса
без поля text:
text not found
Пример
Давайте выведем список ключей, которые есть в
запросе, используя метод has в цикле:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
$keys = ['user', 'text', 'id'];
$res = [];
foreach ($keys as $key) {
if ($bag->has($key)) {
$res[] = $key;
}
}
return new Response(json_encode($res));
}
}
?>
Результат выполнения кода для адреса
/article?user=abcde&id=1:
["user", "id"]