namespace App\Request;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Positive;
use MojtabaGheytasi\RequestValidatorBundle\Request\RequestWithValidation;
class SearchProductRequest extends RequestWithValidation
{
/**
* Get the validation constraints that apply to the request.
*/
protected function constraints(): array
{
return [
'brand' => [
new Length(['min' => 2]),
new Type('string'),
],
'price' => new Collection([
'fields' => [
'min' => [
new Type('integer'),
new Positive(),
],
'max' => [
new Type('integer'),
new Positive(),
],
],
]),
];
}
}
namespace App\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class ProductController
{
public function search(SearchProductRequest $request): Response
{
if ($request->hasError()) {
return new JsonResponse($request->getErrors(), Response::HTTP_BAD_REQUEST);
}
// The incoming request is valid...
// Retrieve one of the validated input data...
$brand = $request->validated('brand'); //gucci
// Retrieve all of the validated input data...
$validated = $request->validated();
// [
// 'brand' => 'gucci',
// 'price' => [
// 'min' => 100,
// 'max' => 1000,
// ]
// ]
}
}
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class ProductController
{
public function search(SearchProductRequest $request): Response
{
$request->hasError(); // true
$request->getErrors(); // returns following array
// [
// "brand": [
// "This value is too short. It should have 2 characters or more."
// ],
// "price": [
// "min": [
// "This value should be of type integer.",
// "This value should be positive."
// ],
// "max": [
// "This value should be of type integer.",
// "This value should be positive."
// ]
// ]
// ]
}
}
if ($request->hasError()) {
return new JsonResponse($request->getErrors(), Response::HTTP_BAD_REQUEST);
}
namespace App\Request\CustomValidation;
use MojtabaGheytasi\RequestValidatorBundle\Contract\FailedValidationInterface;
class FailedValidation implements FailedValidationInterface
{
public function onFailedValidation(array $errors)
{
// Recommend throw an custom exception and handle it with symfony listeners (listen on ExceptionEvent)
// You can find more details on https://symfony.com/doc/4.4/event_dispatcher.html#creating-an-event-listener
}
}
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class ProductController
{
public function search(SearchProductRequest $request): Response
{
// The incoming request is valid...
// Retrieve one of the validated input data...
$brand = $request->validated('brand'); //gucci
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.