8000 [PropertyAccess] fix type error handling when writing values by xabbuh · Pull Request #28220 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/Symfony/Component/PropertyAccess/PropertyAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,12 @@ public static function handleError($type, $message, $file, $line, $context)

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];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ public function addFoo(\DateTime $dateTime)
public function removeFoo(\DateTime $dateTime)
{
}

public function setName($name): self
{
return 'This does not respect the return type on purpose.';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,17 @@ public function testThrowTypeError()
$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();
Expand Down Expand Up @@ -579,4 +590,16 @@ public function testDoNotDiscardReturnTypeError()

$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');
}
}
0