Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Example below tests class property level custom assert validation constraint.


Validation constraint class


namespace Application\BackendBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class Username extends Constraint
{
const INVALID_CONTENT = 'Username must form of only alphabetic and numeric characters.';

public function validatedBy()
{
return get_class($this).'Validator';
}
}

namespace Application\BackendBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UsernameValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (! ctype_alnum($value)) {
$this->context
->buildViolation($constraint::INVALID_CONTENT)
->atPath('username')
->addViolation();
}
}
}

PhpSpec


namespace spec\Application\BackendBundle\Validator\Constraint;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Application\BackendBundle\Validator\Constraint\Username as Constraint;

class UsernameValidatorSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Application\BackendBundle\Validator\Constraint\UsernameValidator');
}

function it_should_not_validate_illegal_characters(
ExecutionContextInterface $context,
ConstraintViolationBuilderInterface $builder,
Constraint $constraint
) {
$this->initialize($context);

$builder->addViolation()->shouldBeCalled();
$builder->atPath('username')->willReturn($builder);

$context->buildViolation(
'Username must form of only alphabetic and numeric characters.'
)->willReturn($builder);

$this->validate('ab@£$123', $constraint);
}

function it_should_validate_legal_value(
ExecutionContextInterface $context,
ConstraintViolationBuilderInterface $builder,
Constraint $constraint
) {
$this->initialize($context);

$builder->addViolation()->shouldNotBeCalled();

$this->validate('inanzzz', $constraint);
}
}