bcastellano / symfony-validator-conditional
Symfony validator for conditional validations based on object properties
Installs: 34 619
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 1
Open Issues: 0
Requires
- php: >=5.3.3
Requires (Dev)
- henrikbjorn/phpspec-code-coverage: 1.0.*@dev
- phpspec/phpspec: ~2.0
- satooshi/php-coveralls: ~1.0
- symfony/validator: ~2.0
This package is not auto-updated.
Last update: 2025-02-01 21:19:53 UTC
README
Symfony Conditional validator
Symfony validator for conditional validations based on object properties
Install
The recommended way to install is through composer:
$ composer require bcastellano/symfony-validator-conditional
or adding to require section in composer.json
Usage
You can use PHP, Annotations, YAML or XML.
Configuration example with PHP
// src/AppBundle/Entity/User.php namespace AppBundle\Entity; use Bcastellano\Symfony\Validator\Constraints\Conditional; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Mapping\ClassMetadata; class User { public static function loadValidatorMetadata(ClassMetadata $metadata) { // property validator usage $metadata->addPropertyConstraint('name', new Conditional(array( 'constraints' => array( new Assert\NotBlank(), ), 'condition' => function($value){ // add login here... $value is object of this property and can be use to check context return $boolean; } ))); // class validator usage $metadata->addConstraint(new Conditional(array( 'constraints' => array( new Assert\Callback('validate'), ), 'condition' => function($value){ // add login here... $value is object validating and can be use to check context return $boolean; } ))); } }
Configuration example with annotations
// src/AppBundle/Entity/User.php namespace AppBundle\Entity; use Bcasellano\Symfony\Validator\Constraints\Conditional; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Mapping\ClassMetadata; /** * Class validator * * @Conditional( * constraints = { * @Assert\Callback({"AppBundle\Entity\User","validate"}) * }, * condition = "AppBundle\Entity\User::shouldValidateName" * ) */ class User { /** * Property validator * * @Conditional( * constraints = { * @Assert\NotBlank() * }, * condition = "AppBundle\Entity\User::shouldValidateName" * ) */ protected $name; public static function shouldValidateName($object) { // add login here... $value is object validating and can be use to check context return $boolean; } public static function validate($object, ExecutionContextInterface $context, $payload) { // ... } }