Skip to content

Commit

Permalink
46867 - Helpful property path accessor exceptions
Browse files Browse the repository at this point in the history
Adds more helpful exceptions when properties cannot be accessed/set
using forms.
Closes symfony/symfony#46867.
  • Loading branch information
patrickmaynard committed Aug 25, 2022
1 parent 0a1a3ea commit ffed7c6
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions Extension/Core/DataAccessor/PropertyPathAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.'
);
}
}
}

Expand All @@ -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;
}
Expand Down

0 comments on commit ffed7c6

Please sign in to comment.