Symfony / Validator: checking properties in a callback

I am trying to create an Address object with a postal code verified based on this country. The transition method is obviously the CallbackValidator. At the moment I have this code:

use SLLH\IsoCodesValidator\Constraints\ZipCode;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Address
{
    /**
     * @Callback()
     */
    public function validatePostalCode(ExecutionContextInterface $context)
    {
        $constraint = new ZipCode([ 'country' => $this->country ]);
        $violations = $context->getValidator()->validate($this->postalCode, $constraint);

        foreach ($violations as $violation) {
            $context->getViolations()->add($violation);
        }
    }
}

The problem is that violations do not have the right path. I do not know how to install it. Also, $context->buildViolation($violation->getMessage())not very good, because I have to manually copy all the properties that may have violations.

EDIT: I tried, and it is really very ugly .

+4
source share
1 answer

. , , . , .

/**
 * @Callback()
 */
public function validatePostalCode(ExecutionContextInterface $context)
{
    $constraint = new ZipCode([ 'country' => $this->country ]);
    $validator = $context->getValidator()->inContext($context);
    $validator->atPath('postalCode')->validate($this->postalCode, $constraint, [Constraint::DEFAULT_GROUP]);
}
+1

Source: https://habr.com/ru/post/1619722/


All Articles