[Validator] Initializes objects before validation

Posted by Awestruck on Tue, 01 Oct 2019 08:16:24 +0200

This is an unusual function for doing something before object validation, such as updating objects and reading object metadata. To use this function, you only need to implement it ObjectInitializerInterface Interface is OK. Here is an example of how to use it.

An object that contains email and username attributes is called AcmeUser:

class AcmeUser
{
    /**
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    private $email;

    /**
     * @Assert\NotBlank()
     */
    private $username;

    // ...
}

The username field violates the validation rules by setting only the email attribute and submitting validation:

$entity = new AcmeUser();
$entity->setEmail('siganushka@gmail.com');

$violationList = $validator->validate($entity);

var_dump((string) $violationList);

// string(118) "Object(App\Entity\AcmeUser).username:
//    This value should not be blank. (code c1051bb4-d103-4f74-8988-acbcafc7fdc3)
// "

Realization ObjectInitializerInterface Interface to change username before validation:

// src/Validator/AcmeUserInitializer.php

use App\Entity\AcmeUser;
use Symfony\Component\Validator\ObjectInitializerInterface;

class AcmeUserInitializer implements ObjectInitializerInterface
{
    public function initialize($object)
    {
        if (!$object instanceof AcmeUser) {
            return;
        }

        list($username, $host) = explode('@', $object->getEmail());
        $object->setUsername($username);
    }
}

The username attribute passed the validation rule at the time of re-validation:

$entity = new AcmeUser();
$entity->setEmail('siganushka@gmail.com');

$violationList = $validator->validate($entity);
if (count($violationList) > 0) {
    var_dump((string) $violationList);
    exit;
}

var_dump($entity);
exit;

// object(App\Entity\AcmeUser)#368 (2) {
//    ["email":"App\Entity\AcmeUser":private]=>
//    string(20) "siganushka@gmail.com"
//    ["username":"App\Entity\AcmeUser":private]=>
//    string(10) "siganushka"
// }

Registration label

Benefit from automatic configuration( autoconfigure ) Options. By default, you don't need to register labels manually, but if you explicitly turn off automatic configuration in services.yaml, or if you're writing an open third-party Bundle The system needs to be labeled manually:

# config/services.yaml

services:
    App\Validator\AcmeUserInitializer
        tags: [ 'validator.initializer' ]

Topics: PHP Attribute