[PropertyAccess] Handle interfaces in the invalid argument exception

This commit is contained in:
Thomas Calvet 2017-01-20 15:18:09 +01:00 committed by Fabien Potencier
parent 77289b9023
commit be52b39031
3 changed files with 33 additions and 1 deletions

View File

@ -246,7 +246,7 @@ class PropertyAccessor implements PropertyAccessorInterface
private static function throwInvalidArgumentException($message, $trace, $i)
{
if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file']) {
$pos = strpos($message, $delim = 'must be of the type ') ?: strpos($message, $delim = 'must be an instance of ');
$pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface '));
$pos += strlen($delim);
$type = $trace[$i]['args'][0];
$type = is_object($type) ? get_class($type) : gettype($type);

View File

@ -18,6 +18,11 @@ class TypeHinted
{
private $date;
/**
* @var \Countable
*/
private $countable;
public function setDate(\DateTime $date)
{
$this->date = $date;
@ -27,4 +32,20 @@ class TypeHinted
{
return $this->date;
}
/**
* @return \Countable
*/
public function getCountable()
{
return $this->countable;
}
/**
* @param \Countable $countable
*/
public function setCountable(\Countable $countable)
{
$this->countable = $countable;
}
}

View File

@ -554,4 +554,15 @@ class PropertyAccessorTest extends \PHPUnit_Framework_TestCase
$this->assertSame('baz', $this->propertyAccessor->getValue($object, 'publicAccessor[value2]'));
$this->assertSame(array('value1' => 'foo', 'value2' => 'baz'), $object->getPublicAccessor());
}
/**
* @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException
* @expectedExceptionMessage Expected argument of type "Countable", "string" given
*/
public function testThrowTypeErrorWithInterface()
{
$object = new TypeHinted();
$this->propertyAccessor->setValue($object, 'countable', 'This is a string, \Countable expected.');
}
}