blixit/symfony-request-validator-bundle
Installation
composer require relief_applications/symfony-request-validator-bundle @dev
(Note: The package name in the README appears incorrect; verify the correct package name via composer search or adjust to blixit/symfony-request-validator-bundle as per the prompt.)
Enable the Bundle
Add to config/bundles.php (Symfony 4+):
return [
// ...
Blixit\RequestValidatorBundle\RequestValidatorBundle::class => ['all' => true],
];
Configure the Bundle
Import services in config/packages/request_validator.yaml (or equivalent):
imports:
- { resource: "@RequestValidatorBundle/Resources/config/services.yml" }
First Validation Use Case
Define a custom constraint class (e.g., src/Validator/Constraints/MyConstraint.php):
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class MyConstraint extends Constraint {
public $message = 'This value should be valid.';
}
Use it in a controller:
use App\Validator\Constraints\MyConstraint;
use Symfony\Component\Validator\Validation;
use Symfony\Component\HttpFoundation\Request;
public function validateRequest(Request $request) {
$validator = Validation::createValidator();
$constraint = new MyConstraint();
$errors = $validator->validate($request->request->all(), $constraint);
// Handle errors...
}
Request Validation in Controllers Reuse a base controller to centralize validation logic:
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class BaseController {
protected $validator;
public function __construct(ValidatorInterface $validator) {
$this->validator = $validator;
}
protected function validate(Request $request, $constraint) {
return $this->validator->validate($request->request->all(), $constraint);
}
}
Form Validation Extend Symfony’s form validation with custom constraints:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use App\Validator\Constraints\MyConstraint;
class MyFormType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('field', null, [
'constraints' => [new MyConstraint()],
]);
}
}
API Request Validation Validate JSON payloads in API endpoints:
public function apiEndpoint(Request $request) {
$data = json_decode($request->getContent(), true);
$constraint = new MyConstraint();
$errors = $this->validator->validate($data, $constraint);
if (count($errors) > 0) {
return $this->json(['errors' => (string) $errors], 400);
}
// Proceed...
}
Event-Driven Validation
Trigger validation via Symfony events (e.g., kernel.request):
# config/services.yaml
services:
App\EventListener\RequestValidatorListener:
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RequestValidatorListener {
public function __construct(private ValidatorInterface $validator) {}
public function onKernelRequest(RequestEvent $event) {
$request = $event->getRequest();
if ($request->isXmlHttpRequest() || $request->getPathInfo() === '/api') {
$constraint = new MyConstraint();
$errors = $this->validator->validate($request->request->all(), $constraint);
if (count($errors) > 0) {
$event->setResponse(new JsonResponse(['errors' => (string) $errors], 400));
}
}
}
}
Bundle Name Mismatch
The README references relief_applications/symfony-request-validator-bundle, but the prompt specifies blixit/symfony-request-validator-bundle. Verify the correct package name to avoid installation errors.
Symfony Version Compatibility
The bundle may not support Symfony 5.3+ out of the box. Check the bundle’s composer.json for required Symfony versions or fork the bundle if needed.
Constraint Class Requirements
Custom constraints must extend Symfony\Component\Validator\Constraint and define:
message property (for error messages).validatedBy method (to specify a validator class).
Example:class MyConstraint extends Constraint {
public $message = 'Custom error message.';
public function validatedBy() { return static::class . 'Validator'; }
}
Validator Service Binding
The bundle may not auto-configure the validator service. Manually bind it in config/services.yaml:
services:
Symfony\Component\Validator\Validator\ValidatorInterface: '@validator'
Performance Overhead
Avoid validating every request globally (e.g., in kernel.request). Instead, validate only when necessary (e.g., in specific controllers or routes).
Enable Validator Debugging
Add this to config/packages/validator.yaml:
validator:
enable_annotation_reader: true
enable_attribute_reader: true
Inspect Validation Errors
Use dump() to debug errors:
$errors = $validator->validate($data, $constraint);
dump((string) $errors); // Convert errors to a string for debugging
Constraint-Specific Debugging
For custom constraints, implement a validator class (e.g., MyConstraintValidator) and use dump() to inspect values:
use Symfony\Component\Validator\ConstraintValidator;
class MyConstraintValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
dump($value); // Debug input
// Validation logic...
}
}
Custom Validators Extend the bundle by creating reusable validators:
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class EmailDomainValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
if (!preg_match('/@example\.com$/', $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $value)
->addViolation();
}
}
}
Dynamic Constraints Pass dynamic values to constraints:
class DynamicConstraint extends Constraint {
public $allowedValues = [];
public $message = 'Value "{{ value }}" is not allowed.';
}
Usage:
$constraint = new DynamicConstraint(['allowedValues' => [1, 2, 3]]);
Integration with API Platform Use the bundle’s constraints in API Platform resources:
# config/api_platform/resources.yaml
App\Entity\MyEntity:
attributes:
validation_context:
enabled: true
constraints:
- App\Validator\Constraints\MyConstraint
Testing Validations Write PHPUnit tests for constraints:
use Symfony\Component\Validator\Validation;
use App\Validator\Constraints\MyConstraint;
public function testConstraint() {
$validator = Validation::createValidator();
$constraint = new MyConstraint();
$errors = $validator->validate('invalid', $constraint);
$this->assertCount(1, $errors);
}
How can I help you explore Laravel packages today?