Closed
Description
Description
As far as I understood, the reason why people use the PropertyAccess component instead of making all properties public and accessing them directly is because they want to protect their object's state from certain, invalid, transformations.
Now if a class defines an addX
function without a removeX
function for its objects, it obviously wants to protect the state from changes where an X is removed.
The correct way of handling this IMHO would be throwing an exception when state changes like this occur.
Currently, the PropertyAccess throws an exception whenever the remove
method is not defined, even when removals where not even attempted instead.
Example
public class Post {
public function __construct(
private array $comments,
){}
public function getComments(): array
{
return $this->comments;
}
public function addComment(string $comment): void
{
$this->comments[] = $comment;
}
}
$propertyAccessor = new \Symfony\Component\PropertyAccess\PropertyAccessor();
$post = new Post([]);
// this should be allowed, but throws an Exception currently:
$propertyAccessor->setValue($post, 'comments', ['Nice, bro!', 'Amazing post!']);
// this should rightfully throw an Exception, because posts are protected from comment removals:
$propertyAccessor->setValue($post, 'comments', ['Nice, bro!']);