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 Validator Laravel Package

spiral-packages/symfony-validator

Symfony Validator bridge for the Spiral Framework. Integrates Symfony’s validation component into Spiral apps, providing familiar constraints and error handling. Includes CI, static analysis, and type coverage. Documentation available at spiral.dev.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require spiral-packages/symfony-validator:^1.5.0
    

    Add the package to your Spiral Framework bootstrap.php:

    $container->set(SymfonyValidator::class, fn() => new SymfonyValidator());
    
  2. First Use Case: Basic Validation (Symfony 7.0 Compatible) Define a validator in a command or controller:

    use Spiral\Validator\ValidatorInterface;
    use Spiral\Validator\Rule\StringRule;
    
    $validator = $container->get(ValidatorInterface::class);
    $result = $validator->validate([
        'name' => 'John Doe',
        'email' => 'invalid-email'
    ], [
        'name' => [new StringRule(['min' => 2])],
        'email' => [new StringRule(['email' => true])]
    ]);
    
  3. Key Files to Review

    • src/ValidatorInterface.php (Core interface)
    • src/SymfonyValidator.php (Updated bridge for Symfony 7.0)
    • src/Rule/ (Predefined rules, now compatible with Symfony 7.0 constraints)
    • src/Constraint/ (Newly added or updated Symfony constraint mappings)

Implementation Patterns

Common Workflows

1. Request Validation (API/HTTP)

Use with Spiral's HTTP layer for incoming requests:

use Spiral\Http\Middleware\ValidationMiddleware;

$middleware = new ValidationMiddleware(
    $validator,
    [
        'email' => [new StringRule(['email' => true])],
        'age' => [new NumericRule(['min' => 18])]
    ]
);

2. Form/Entity Validation

Validate domain entities before persistence:

$user = new User($data);
$result = $validator->validateObject($user, [
    'email' => [new StringRule(['email' => true])],
    'password' => [new StringRule(['min' => 8])]
]);

3. Dynamic Rules (Runtime Validation)

Build rules programmatically:

$rules = [];
if ($isAdmin) {
    $rules['role'] = [new InRule(['values' => ['admin']])];
}
$validator->validate($data, $rules);

4. Custom Rules (Symfony 7.0 Constraints)

Extend Symfony 7.0 constraints for Spiral:

use Symfony\Component\Validator\Constraint;
use Spiral\Validator\Rule\CustomRule;

class UniqueUsernameRule extends CustomRule {
    protected function getSymfonyConstraint(): Constraint {
        return new \Symfony\UX\Validator\Constraints\UniqueEntity(['entity' => User::class, 'fields' => 'username']);
    }
}

5. Integration with Spiral's DI

Bind validator to specific contexts (e.g., CLI vs. HTTP):

$container->bindInterface(
    ValidatorInterface::class,
    fn() => new SymfonyValidator(['context' => 'cli'])
);

6. Symfony 7.0-Specific Features

Leverage Symfony 7.0's new constraints (e.g., Url, Ipv4, Ipv6):

use Spiral\Validator\Rule\UrlRule;

$rules = [
    'website' => [new UrlRule()]
];

Gotchas and Tips

Pitfalls

  1. Rule Mismatch (Symfony 7.0 Updates)

    • Symfony 7.0 may introduce breaking changes in constraint classes (e.g., NotBlankNotNull for certain types).
    • Fix: Use CustomRule for complex Symfony 7.0 constraints or check the Symfony 7.0 migration guide.
  2. Lazy Loading

    • Symfony's validator may throw UndefinedIndex if data keys don’t match rules.
    • Fix: Use null as default for missing fields:
      $result = $validator->validate(array_merge($data, ['missing_field' => null]), $rules);
      
  3. Performance

    • Compile rules for repeated validation:
      $compiled = $validator->compileRules($rules);
      $validator->validate($data, $compiled);
      
  4. Doctrine Integration (Symfony 7.0)

    • If using UniqueEntity, ensure Doctrine is loaded first and compatible with Symfony 7.0:
      $container->set(DoctrineValidator::class, fn() => new DoctrineValidator($entityManager));
      

Debugging Tips

  • Detailed Errors: Enable Symfony 7.0's validator groups:
    $validator->validate($data, $rules, ['groups' => ['default', 'strict']]);
    
  • Rule Inspection: Dump compiled rules:
    $compiled = $validator->compileRules($rules);
    var_dump($compiled);
    
  • Symfony Validator Dump: Access the underlying validator:
    $symfonyValidator = $container->get(SymfonyValidator::class)->getValidator();
    $symfonyValidator->validate($data, $constraints);
    

Extension Points

  1. Custom Error Messages Override Symfony's messages in Spiral's rules:

    new StringRule(['min' => 3, 'message' => 'Name must be at least 3 characters.']);
    
  2. Validation Groups (Symfony 7.0) Use Symfony 7.0's groups for modular validation:

    $validator->validate($data, $rules, ['groups' => ['registration', 'profile']]);
    
  3. Event Listeners Attach Spiral events to validation:

    $container->pipe(
        OnValidateEvent::class,
        fn(OnValidateEvent $event) => $event->setData($this->sanitize($event->getData()))
    );
    
  4. Testing Mock the validator in tests:

    $validatorMock = Mockery::mock(ValidatorInterface::class);
    $validatorMock->shouldReceive('validate')->andReturn(['errors' => []]);
    $container->set(ValidatorInterface::class, $validatorMock);
    
  5. Symfony 7.0 Constraint Updates

    • Check for deprecated constraints (e.g., LengthStringLength):
      use Spiral\Validator\Rule\StringLengthRule;
      $rules = ['name' => [new StringLengthRule(['max' => 50])]];
      
  6. New Symfony 7.0 Features

    • Use Expression constraint for complex logic:
      use Spiral\Validator\Rule\ExpressionRule;
      $rules = ['age' => [new ExpressionRule('this > 18', 'You must be over 18.')]];
      
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope