Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Symfony Request Validator Bundle Laravel Package

blixit/symfony-request-validator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. 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.)

  2. Enable the Bundle Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        Blixit\RequestValidatorBundle\RequestValidatorBundle::class => ['all' => true],
    ];
    
  3. Configure the Bundle Import services in config/packages/request_validator.yaml (or equivalent):

    imports:
        - { resource: "@RequestValidatorBundle/Resources/config/services.yml" }
    
  4. 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...
    }
    

Implementation Patterns

Common Workflows

  1. 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);
        }
    }
    
  2. 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()],
                ]);
        }
    }
    
  3. 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...
    }
    
  4. 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));
                }
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. 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.

  2. 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.

  3. Constraint Class Requirements Custom constraints must extend Symfony\Component\Validator\Constraint and define:

    • A message property (for error messages).
    • Optionally, a validatedBy method (to specify a validator class). Example:
    class MyConstraint extends Constraint {
        public $message = 'Custom error message.';
        public function validatedBy() { return static::class . 'Validator'; }
    }
    
  4. 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'
    
  5. Performance Overhead Avoid validating every request globally (e.g., in kernel.request). Instead, validate only when necessary (e.g., in specific controllers or routes).

Debugging Tips

  1. Enable Validator Debugging Add this to config/packages/validator.yaml:

    validator:
        enable_annotation_reader: true
        enable_attribute_reader: true
    
  2. Inspect Validation Errors Use dump() to debug errors:

    $errors = $validator->validate($data, $constraint);
    dump((string) $errors); // Convert errors to a string for debugging
    
  3. 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...
        }
    }
    

Extension Points

  1. 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();
            }
        }
    }
    
  2. 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]]);
    
  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
    
  4. 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);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle