Permalink
Browse files

feature #27586 [PropertyAccess] Add Property Path to Exception Messag…

…e (rodnaph)

This PR was merged into the 4.2-dev branch.

Discussion
----------

[PropertyAccess] Add Property Path to Exception Message

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | None
| License       | MIT
| Doc PR        | None

When an exception is thrown writing a property it is not currently obvious which path is at fault (eg. `Expected argument of type "%s", "%s" given` - but where?). This patch appends the current property path to the exception so it is clear which path caused the error (eg. `Expected argument of type "%s", "%s" given at property path "foo.bar"`)

Commits
-------

473a025 add property path to exception message when error writing property
  • Loading branch information...
fabpot committed Jun 25, 2018
2 parents 5fe78a3 + 473a025 commit d871473ef2f004cdfe9eb29289ec0ef9b58c3948
@@ -151,22 +151,22 @@ public function setValue(&$objectOrArray, $propertyPath, $value)
$value = $zval[self::VALUE];
}
} catch (\TypeError $e) {
self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0);
self::throwInvalidArgumentException($e->getMessage(), $e->getTrace(), 0, $propertyPath);
// It wasn't thrown in this class so rethrow it
throw $e;
}
}
private static function throwInvalidArgumentException($message, $trace, $i)
private static function throwInvalidArgumentException($message, $trace, $i, $propertyPath)
{
if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && isset($trace[$i]['args'][0])) {
$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);
throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given.', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type));
throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given at property path "%s".', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type, $propertyPath));
}
}
@@ -529,7 +529,7 @@ public function testIsWritableForReferenceChainIssue($object, $path, $value)
/**
* @expectedException \Symfony\Component\PropertyAccess\Exception\InvalidArgumentException
* @expectedExceptionMessage Expected argument of type "DateTime", "string" given
* @expectedExceptionMessage Expected argument of type "DateTime", "string" given at property path "date"
*/
public function testThrowTypeError()
{

0 comments on commit d871473

Please sign in to comment.