I would use a custom validator. Here's an example from one of my projects (3.4).
Three files:
<?php // src/AppBundle/Validator/Constraint/HasValidDimensions.php
namespace AppBundle\Validator\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class HasValidDimensions extends Constraint
{
public $invalidWidth = 'Invalid width dimension.';
public $invalidHeight = 'Invalid height dimension.';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
Note the use of CLASS_CONSTRAINT. Now, the actual validator gives me access to the different parts (in this case it's a command validator):
<?php // src/AppBundle/Validator/Constraint/HasValidDimensionsValidator.php
namespace AppBundle\Validator\Constraint;
use AppBundle\Message\Command\PageTemplate\SetPageTemplateDimensions;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* @Annotation
*/
class HasValidDimensionsValidator extends ConstraintValidator
{
public function validate($setPageTemplateDimensions, Constraint $constraint): void
{
/* @var SetPageTemplateDimensions $setPageTemplateDimensions */
/* @var HasValidDimensions $constraint */
$pageTemplate = $setPageTemplateDimensions->getPageTemplate();
if ($setPageTemplateDimensions->getWidth() > $pageTemplate->getWidthReal()) {
$this->context
->buildViolation($constraint->invalidWidth)
->addViolation()
;
}
if ($setPageTemplateDimensions->getHeight() > $pageTemplate->getHeightReal()) {
$this->context
->buildViolation($constraint->invalidHeight)
->addViolation()
;
}
}
}
Then use the validator on the class:
<?php // src/AppBundle/Message/Command/PageTemplate/SetPageTemplateDimensions.php
namespace AppBundle\Message\Command\PageTemplate;
use AppBundle\Validator\Constraint as AppAssert;
/**
* @AppAssert\HasValidDimensions()
*/
class SetPageTemplateDimensions implements TenantOwnedInterface
{