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
Say you have an object, and you want to create an exact copy of it with a very little adjustments.
How would you do it? Yo'd have to create a new object of the same class and then you have to go through all the fields of the original object and copy their values over to the new object:
$newConstraintViolation =newConstraintViolation($violation->getMessage(),$violation->getMessageTemplate(),$violation->getParameters(),$root,$propertyPath,$violation->getInvalidValue(),$violation->getPlural(),$violation->getCode(),$violation->getConstraint(),$violation->getCause(),);
This code does nothing else but creates a new instance ofConstraintViolation
from the existing$violation
with specific$root
and$propertyPath
fields. The rest of the fields remain the same as in the original object.
IMO, it's quite hard to support this kind of cloning in the client code, since whenever new parameters are added toConstraintViolation
or any of the existing parameters are renamed/reordered/deleted, this cloning code would require manual adjustments during symfony upgrade. The developer would need to update the arguments list to match to the latest version ofConstraintViolation
in updated symfony.
I suggest to add these methods toConstraintViolation
class andConstraintViolationInterface
:
publicfunctionwithMessage(string|\Stringable$message):static{$violation =clone$this;$violation->message =$message;return$violation;}publicfunctionwithMessageTemplate(string$messageTemplate):static{$violation =clone$this;$violation->messageTemplate =$messageTemplate;return$violation;}publicfunctionwithParameters(array$parameters):static{$violation =clone$this;$violation->parameters =$parameters;return$violation;}publicfunctionwithPlural(?int$plural):static{$violation =clone$this;$violation->plural =$plural;return$violation;}publicfunctionwithRoot(mixed$root):static{$violation =clone$this;$violation->root =$root;return$violation;}publicfunctionwithPropertyPath(string$propertyPath):static{$violation =clone$this;$violation->propertyPath =$propertyPath;return$violation;}publicfunctionwithInvalidValue(mixed$invalidValue):static{$violation =clone$this;$violation->invalidValue =$invalidValue;return$violation;}publicfunctionwithCode(?string$code):static{$violation =clone$this;$violation->code =$code;return$violation;}publicfunctionwithConstraint(?Constraint$constraint):static{$violation =clone$this;$violation->constraint =$constraint;return$violation;}publicfunctionwithCause(mixed$cause):static{$violation =clone$this;$violation->cause =$cause;return$violation;}
Therefore, original code could be written this way:
$newConstraintViolation =$violation->withRoot($root)->withPropertyPath($propertyPath);
Please, let me know what you think about this proposal.
Thank you!
Example
No response