bug #28220 [PropertyAccess] fix type error handling when writing values (xabbuh)
This PR was merged into the 2.8 branch.
Discussion
----------
[PropertyAccess] fix type error handling when writing values
| Q | A
| ------------- | ---
| Branch? | 2.8
| Bug fix? | yes
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets |
| License | MIT
| Doc PR |
Commits
-------
45754515a5
fix type error handling when writing values
This commit is contained in:
commit
e18bf6eee0
@ -231,7 +231,12 @@ class PropertyAccessor implements PropertyAccessorInterface
|
||||
|
||||
private static function throwInvalidArgumentException($message, $trace, $i)
|
||||
{
|
||||
if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && isset($trace[$i]['args'][0])) {
|
||||
// the type mismatch is not caused by invalid arguments (but e.g. by an incompatible return type hint of the writer method)
|
||||
if (0 !== strpos($message, 'Argument ')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && array_key_exists(0, $trace[$i]['args'])) {
|
||||
$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];
|
||||
|
@ -28,4 +28,9 @@ class ReturnTyped
|
||||
public function removeFoo(\DateTime $dateTime)
|
||||
{
|
||||
}
|
||||
|
||||
public function setName($name): self
|
||||
{
|
||||
return 'This does not respect the return type on purpose.';
|
||||
}
|
||||
}
|
||||
|
@ -538,6 +538,17 @@ class PropertyAccessorTest extends TestCase
|
||||
$this->propertyAccessor->setValue($object, 'date', 'This is a string, \DateTime expected.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException
|
||||
* @expectedExceptionMessage Expected argument of type "DateTime", "NULL" given
|
||||
*/
|
||||
public function testThrowTypeErrorWithNullArgument()
|
||||
{
|
||||
$object = new TypeHinted();
|
||||
|
||||
$this->propertyAccessor->setValue($object, 'date', null);
|
||||
}
|
||||
|
||||
public function testSetTypeHint()
|
||||
{
|
||||
$date = new \DateTime();
|
||||
@ -579,4 +590,16 @@ class PropertyAccessorTest extends TestCase
|
||||
|
||||
$this->propertyAccessor->setValue($object, 'foos', array(new \DateTime()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @requires PHP 7
|
||||
*
|
||||
* @expectedException \TypeError
|
||||
*/
|
||||
public function testDoNotDiscardReturnTypeErrorWhenWriterMethodIsMisconfigured()
|
||||
{
|
||||
$object = new ReturnTyped();
|
||||
|
||||
$this->propertyAccessor->setValue($object, 'name', 'foo');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user