8000 [PropertyAccess] Throw an InvalidArgumentException when the type do not match by dunglas · Pull Request #17738 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[PropertyAccess] Throw an InvalidArgumentException when the type do not match #17738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[PropertyAccess] Throw an InvalidArgumentException when the type do n…
…ot match
  • Loading branch information
dunglas committed Feb 9, 2016
commit 1329eb6479f22e90588a2929314b0cffbb7edca8
38 changes: 34 additions & 4 deletions src/Symfony/Component/PropertyAccess/PropertyAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\PropertyAccess;

use Symfony\Component\PropertyAccess\Exception\AccessException;
use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
Expand Down Expand Up @@ -553,7 +554,7 @@ private function writeProperty(&$object, $property, $value)
$access = $this->getWriteAccessInfo($object, $property, $value);

if (self::ACCESS_TYPE_METHOD === $access[self::ACCESS_TYPE]) {
$object->{$access[self::ACCESS_NAME]}($value);
$this->callMethod($object, $access[self::ACCESS_NAME], $value);
} elseif (self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]) {
$object->{$access[self::ACCESS_NAME]} = $value;
} elseif (self::ACCESS_TYPE_ADDER_AND_REMOVER === $access[self::ACCESS_TYPE]) {
Expand All @@ -567,12 +568,41 @@ private function writeProperty(&$object, $property, $value)

$object->$property = $value;
} elseif (self::ACCESS_TYPE_MAGIC === $access[self::ACCESS_TYPE]) {
$object->{$access[self::ACCESS_NAME]}($value);
$this->callMethod($object, $access[self::ACCESS_NAME], $value);
} else {
throw new NoSuchPropertyException($access[self::ACCESS_NAME]);
}
}

/**
* Call a method and convert {@see \TypeError} to {@see InvalidArgumentException}.
*
* @param object $object
* @param string $method
* @param mixed $value
*/
private function callMethod($object, $method, $value) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{ should be on the next line

if (class_exists('TypeError')) {
// PHP 7
try {
$object->{$method}($value);
} catch (\TypeError $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}

// PHP 5
set_error_handler(function ($errno, $errstr) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for disturbing.
Maybe better to use something like this:

set_error_handler(function ($errno, $errstr) use ($object, $method) {
    if (E_RECOVERABLE_ERROR === $errno && false !== strpos($errstr, sprintf('passed to %s::%s() must', get_class($object), $method))) {
        throw new InvalidArgumentException($errstr);
    }

    return false;
});

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to not test the error message. It's not clean and it still does not handle all cases. Throwing an error (and not an exception) in a mutator should be very very rare in a real code.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What cases it does not handle?
If found no other messages in PHP source that match used pattern:
https://github.com/php/php-src/blob/be607e724c69c92f8cda72a45a13a26e7c439aec/Zend/zend_execute.c#L644
https://github.com/php/php-src/blob/be607e724c69c92f8cda72a45a13a26e7c439aec/Zend/zend_execute.c#L648
https://github.com/php/php-src/blob/be607e724c69c92f8cda72a45a13a26e7c439aec/Zend/zend_execute.c#L651

And it seems that message is same for all supported PHP 5 versions: https://3v4l.org/VZhkg
I prefer to use more bullet proof solution than relying that something wont happen

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A user can trigger an error with the same or a similar message.

What do you think about that @symfony/deciders

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Users are not supposed to trigger errors with E_RECOVERABLE_ERROR type (there are specific ones with USER_...). So if there are other E_RECOVERABLE_ERROR errors that could be triggered by PHP here, we need to make sure only type errors are handled.

throw new InvalidArgumentException($errstr);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are you not checking for E_RECOVERABLE_ERROR === $errno as notice/warning generated in method call will lead to InvalidArgumentException?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea thanks

});

try {
$object->{$method}($value);
} finally {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may cause issues with PHP < 5.6 (a.k.a 5.5), which have a bugged implementation of finally.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

restore_error_handler();
}
}

/**
* Adjusts a collection-valued property by calling add*() and remove*()
* methods.
Expand Down Expand Up @@ -613,11 +643,11 @@ private function writeCollection($object, $property, $collection, $addMethod, $r
}

foreach ($itemToRemove as $item) {
$object->{$removeMethod}($item);
$this->callMethod($object, $removeMethod, $item);
}

foreach ($itemsToAdd as $item) {
$object->{$addMethod}($item);
$this->callMethod($object, $addMethod, $item);
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/PropertyAccess/Tests/Fixtures/TestClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class TestClass
private $publicIsAccessor;
private $publicHasAccessor;
private $publicGetter;
private $date;

public function __construct($value)
{
Expand Down Expand Up @@ -173,4 +174,14 @@ public function getPublicGetter()
{
return $this->publicGetter;
}

public function setDate(\DateTimeInterface $date)
{
$this->date = $date;
}

public function getDate()
{
return $this->date;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\PropertyAccess\Tests;

use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClass;
Expand Down Expand Up @@ -510,4 +511,21 @@ public function testIsWritableForReferenceChainIssue($object, $path, $value)
{
$this->assertEquals($value, $this->propertyAccessor->isWritable($object, $path));
}

/**
* @expectedException InvalidArgumentException
*/
public function testConvertTypeErrorToInvalidArgumentException()
{
$this->propertyAccessor->setValue(new TestClass('Kévin'), 'date', 'This is a string, \DateTime excepted.');
}

public function testSetTypeHint()
{
$date = new \DateTimeImmutable();
$object = new TestClass('Kévin');

$this->propertyAccessor->setValue($object, 'date', $date);
$this->assertSame($date, $object->getDate());
}
}
0