Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork9.6k
Description
Description
I propose extending Property Accessor with an optional feature that could enable checking whether object setter has a non-nullable parameter and would call unset($object->parameter) instead of $object->setParameter($value) if $value is null and $object implements __unset() method.
If it makes sense I would create PR for this. I prototyped it and it works but I want to discuss the idea first before creating a full PR (with tests and everything).
Motivation
Form component could use this feature and reset non-nullable properties to uninitialized state when null value is submitted for a non-nullable property. Currently when a NotNull constraint is set on a property it is only evaluated for a new object (with uninitialized properties). Once the value for the property is set (for example through Doctrine hydration) and a user submits an empty/null value the constraint is never evaluated because execution fails on Property Accessor trying to call setter with non-nullable parameter.
Example
class User{privatestring$name;publicfunctionsetName(string$name) {$this->name =$name; }publicfunction__unset($property) { unset($this->$property); }}$user =newUser;$propertyAccessor->setValue($user,'name','John');// $user->setName('John') is called$propertyAccessor->setValue($user,'name',null);// Fatal error: User::setName(): Argument #1 ($name) must be of type string, null given$propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableMagicUnset() ->getPropertyAccessor();$propertyAccessor->setValue($user,'name',null);// unset($user->name) is called