[Validator] Throwing exception in ConstraintValidator::setMessage() if initialize() wasn't called

This commit is contained in:
Bernhard Schussek 2012-02-05 10:03:22 +01:00
parent 6e60967827
commit 78c145196b
2 changed files with 66 additions and 0 deletions

View File

@ -18,6 +18,8 @@ namespace Symfony\Component\Validator;
*
* @api
*/
use Symfony\Component\Validator\Exception\ValidatorException;
abstract class ConstraintValidator implements ConstraintValidatorInterface
{
/**
@ -79,6 +81,10 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
$this->messageTemplate = $template;
$this->messageParameters = $parameters;
if (!$this->context instanceof ExecutionContext) {
throw new ValidatorException('ConstraintValidator::initialize() must be called before setting violation messages');
}
$this->context->addViolation($template, $parameters);
}
}

View File

@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Tests\Component\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ConstraintValidatorTest_Validator extends ConstraintValidator
{
private $message;
private $params;
public function __construct($message, array $params = array())
{
$this->message = $message;
$this->params = $params;
}
public function isValid($value, Constraint $constraint)
{
$this->setMessage($this->message, $this->params);
}
}
class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
{
public function testSetMessage()
{
$context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$constraint = $this->getMock('Symfony\Component\Validator\Constraint', array(), array(), '', false);
$validator = new ConstraintValidatorTest_Validator('error message', array('foo' => 'bar'));
$validator->initialize($context);
$context->expects($this->once())
->method('addViolation')
->with('error message', array('foo' => 'bar'));
$validator->isValid('bam', $constraint);
}
/**
* @expectedException Symfony\Component\Validator\Exception\ValidatorException
*/
public function testSetMessageFailsIfNoContextSet()
{
$constraint = $this->getMock('Symfony\Component\Validator\Constraint', array(), array(), '', false);
$validator = new ConstraintValidatorTest_Validator('error message', array('foo' => 'bar'));
$validator->isValid('bam', $constraint);
}
}