From ffed7c6b0d803b3c9db426dab3c8a27719d28169 Mon Sep 17 00:00:00 2001 From: patrickmaynard Date: Thu, 25 Aug 2022 22:17:58 +0200 Subject: [PATCH] 46867 - Helpful property path accessor exceptions Adds more helpful exceptions when properties cannot be accessed/set using forms. Closes https://github.com/symfony/symfony/issues/46867. --- .../DataAccessor/PropertyPathAccessor.php | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index 57785a896..473f5e22a 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -15,7 +15,9 @@ use Symfony\Component\Form\Exception\AccessException; use Symfony\Component\Form\FormInterface; use Symfony\Component\PropertyAccess\Exception\AccessException as PropertyAccessException; +use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; +use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -66,7 +68,13 @@ public function setValue(object|array &$data, mixed $value, FormInterface $form) // If the data is identical to the value in $data, we are // dealing with a reference if (!\is_object($data) || !$form->getConfig()->getByReference() || $value !== $this->getPropertyValue($data, $propertyPath)) { - $this->propertyAccessor->setValue($data, $propertyPath, $value); + try { + $this->propertyAccessor->setValue($data, $propertyPath, $value); + } catch (NoSuchPropertyException $e) { + throw new NoSuchPropertyException( + $e->getMessage() . ' Make the property public, add a setter, or set the "mapped" field option in the form type to be false.' + ); + } } } @@ -91,13 +99,14 @@ private function getPropertyValue(object|array $data, PropertyPathInterface $pro try { return $this->propertyAccessor->getValue($data, $propertyPath); } catch (PropertyAccessException $e) { - if (\is_array($data) && $e instanceof NoSuchIndexException) { - return null; + if ($e instanceof NoSuchPropertyException) { + throw new NoSuchPropertyException( + $e->getMessage() . ' Make the property public, add a getter, or set the "mapped" field option in the form type to be false.' + ); } - if (!$e instanceof UninitializedPropertyException // For versions without UninitializedPropertyException check the exception message - && (class_exists(UninitializedPropertyException::class) || !str_contains($e->getMessage(), 'You should initialize it')) + && (class_exists(UninitializedPropertyException::class) || false === strpos($e->getMessage(), 'You should initialize it')) ) { throw $e; }