Skip to content

[PropertyAccess] Add nullsafe operator support #34497

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
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
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,14 @@ public function isIndex(int $index)
return $this->isIndex[$index];
}

/**
* {@inheritdoc}
*/
public function isNullSafe(int $index)
{
return false;
}

/**
* Returns whether an element maps directly to a form.
*
Expand Down
16 changes: 13 additions & 3 deletions src/Symfony/Component/PropertyAccess/PropertyAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@ private function readPropertiesUntil(array $zval, PropertyPathInterface $propert
$property = $propertyPath->getElement($i);
$isIndex = $propertyPath->isIndex($i);

$isNullSafe = false;
if (method_exists($propertyPath, 'isNullSafe')) {
// To be removed in symfony 6 once we are sure isNullSafe is always implemented.
$isNullSafe = $propertyPath->isNullSafe($i);
}
Copy link
Member

Choose a reason for hiding this comment

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

I think we need to add an else clause here to raise a deprecation notice to help people with upgrading their code.


if ($isIndex) {
// Create missing nested arrays on demand
if (($zval[self::VALUE] instanceof \ArrayAccess && !$zval[self::VALUE]->offsetExists($property)) ||
Expand Down Expand Up @@ -340,12 +346,14 @@ private function readPropertiesUntil(array $zval, PropertyPathInterface $propert
}

$zval = $this->readIndex($zval, $property);
} elseif ($isNullSafe && !\is_object($zval[self::VALUE])) {
$zval[self::VALUE] = null;
} else {
$zval = $this->readProperty($zval, $property, $this->ignoreInvalidProperty);
$zval = $this->readProperty($zval, $property, $this->ignoreInvalidProperty, $isNullSafe);
}

// the final value of the path must not be validated
if ($i + 1 < $propertyPath->getLength() && !\is_object($zval[self::VALUE]) && !\is_array($zval[self::VALUE])) {
if ($i + 1 < $propertyPath->getLength() && !\is_object($zval[self::VALUE]) && !\is_array($zval[self::VALUE]) && !$isNullSafe) {
throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, $i + 1);
}

Expand Down Expand Up @@ -399,7 +407,7 @@ private function readIndex(array $zval, $index): array
*
* @throws NoSuchPropertyException If $ignoreInvalidProperty is false and the property does not exist or is not public
*/
private function readProperty(array $zval, string $property, bool $ignoreInvalidProperty = false): array
private function readProperty(array $zval, string $property, bool $ignoreInvalidProperty = false, $isNullSafe = false): array
{
if (!\is_object($zval[self::VALUE])) {
throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property));
Expand Down Expand Up @@ -455,6 +463,8 @@ private function readProperty(array $zval, string $property, bool $ignoreInvalid
if (isset($zval[self::REF])) {
$result[self::REF] = &$object->$property;
}
} elseif ($isNullSafe) {
$result[self::VALUE] = null;
} elseif (!$ignoreInvalidProperty) {
throw new NoSuchPropertyException(sprintf('Can\'t get a way to read the property "%s" in class "%s".', $property, $class));
}
Expand Down
29 changes: 29 additions & 0 deletions src/Symfony/Component/PropertyAccess/PropertyPath.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ class PropertyPath implements \IteratorAggregate, PropertyPathInterface
*/
private $isIndex = [];

/**
* Contains a Boolean for each property in $elements denoting whether this
* element is optional or not.
*
* @var array
*/
private $isNullSafe = [];

/**
* String representation of the path.
*
Expand All @@ -72,6 +80,7 @@ public function __construct($propertyPath)
$this->elements = $propertyPath->elements;
$this->length = $propertyPath->length;
$this->isIndex = $propertyPath->isIndex;
$this->isNullSafe = $propertyPath->isNullSafe;
$this->pathAsString = $propertyPath->pathAsString;

return;
Expand Down Expand Up @@ -100,6 +109,13 @@ public function __construct($propertyPath)
$this->isIndex[] = true;
}

// Mark as optional when last character is "?".
if ('?' === substr($element, -1, 1)) {
$this->isNullSafe[] = true;
$element = substr($element, 0, -1);
} else {
$this->isNullSafe[] = false;
}
$this->elements[] = $element;

$position += \strlen($matches[1]);
Expand Down Expand Up @@ -145,6 +161,7 @@ public function getParent()
$parent->pathAsString = substr($parent->pathAsString, 0, max(strrpos($parent->pathAsString, '.'), strrpos($parent->pathAsString, '[')));
array_pop($parent->elements);
array_pop($parent->isIndex);
array_pop($parent->isNullSafe);

return $parent;
}
Expand Down Expand Up @@ -202,4 +219,16 @@ public function isIndex(int $index)

return $this->isIndex[$index];
}

/**
* {@inheritdoc}
*/
public function isNullSafe(int $index)
{
if (!isset($this->isNullSafe[$index])) {
throw new OutOfBoundsException(sprintf('The index %s is not within the property path', $index));
}

return $this->isNullSafe[$index];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* A sequence of property names or array indices.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @method bool isNullSafe(int $index) Returns whether the element at the given index is null sage. Not implementing it is deprecated since Symfony 5.2
*/
interface PropertyPathInterface extends \Traversable
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public function getPathsWithMissingIndex()
}

/**
* @dataProvider getValidPropertyPaths
* @dataProvider getValidReadPropertyPaths
*/
public function testGetValue($objectOrArray, $path, $value)
{
Expand Down Expand Up @@ -308,7 +308,7 @@ public function testGetValueThrowsExceptionIfNotObjectOrArray($objectOrArray, $p
}

/**
* @dataProvider getValidPropertyPaths
* @dataProvider getValidWritePropertyPaths
*/
public function testSetValue($objectOrArray, $path)
{
Expand Down Expand Up @@ -433,7 +433,7 @@ public function testGetValueWhenArrayValueIsNull()
}

/**
* @dataProvider getValidPropertyPaths
* @dataProvider getValidReadPropertyPaths
*/
public function testIsReadable($objectOrArray, $path)
{
Expand Down Expand Up @@ -505,7 +505,7 @@ public function testIsReadableReturnsFalseIfNotObjectOrArray($objectOrArray, $pa
}

/**
* @dataProvider getValidPropertyPaths
* @dataProvider getValidWritePropertyPaths
*/
public function testIsWritable($objectOrArray, $path)
{
Expand Down Expand Up @@ -576,7 +576,7 @@ public function testIsWritableReturnsFalseIfNotObjectOrArray($objectOrArray, $pa
$this->assertFalse($this->propertyAccessor->isWritable($objectOrArray, $path));
}

public function getValidPropertyPaths()
public function getValidWritePropertyPaths()
{
return [
[['Bernhard', 'Schussek'], '[0]', 'Bernhard'],
Expand Down Expand Up @@ -622,6 +622,19 @@ public function getValidPropertyPaths()
];
}

public function getValidReadPropertyPaths()
{
$testCases = $this->getValidWritePropertyPaths();

// Optional paths can only be read and can't be written to.
$testCases[] = [(object) ['foo' => (object) ['firstName' => 'Bernhard']], 'foo.bar?', null];
$testCases[] = [(object) ['foo' => (object) ['firstName' => 'Bernhard']], 'foo.bar?.baz?', null];
$testCases[] = [['foo' => ['firstName' => 'Bernhard']], '[foo][bar?]', null];
$testCases[] = [['foo' => ['firstName' => 'Bernhard']], '[foo][bar?][baz?]', null];

return $testCases;
}

public function testTicket5755()
{
$object = new Ticket5775Object();
Expand Down