PHP code example of bcastellano / symfony-validator-conditional

1. Go to this page and download the library: Download bcastellano/symfony-validator-conditional library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bcastellano / symfony-validator-conditional example snippets


// 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; 
            }
        )));
    }
}

// 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)
    {
        // ...
    }
}