-
-
Notifications
You must be signed in to change notification settings - Fork 162
[Feature] Add private properties interception #412
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
Conversation
$backTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $stackLevel+1); | ||
$accessor = $backTrace[$stackLevel] ?? []; | ||
$propertyClass = $property->class; | ||
if (isset($accessor['class'])) { | ||
if ($accessor['class'] === $propertyClass || is_subclass_of($accessor['class'], $propertyClass)) { | ||
// For private and protected properties its ok to access from the same class |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍
return; | ||
} | ||
// For protected properties its ok to access from any subclass | ||
if ($isProtected && is_subclass_of($accessor['class'], $propertyClass)) { | ||
return; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The exception message in line 137 below is probably no longer accurate: Cannot access protected property...
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, somehow have forgotten about this line )
This was quick! Thank you for your hard work! 🍺 With this PR, my code to set private's property value from an aspect works now: $setter = \Closure::bind(function ($object, $value) use ($field) {
$object->$field = $value;
}, null, \get_parent_class($fieldAccess->getThis()));
$setter($fieldAccess->getThis(), 'some value'); Not sure if you expect the below code to work as well ('cause it doesn't): $fieldAccess->getField()->setAccessible(true);
$fieldAccess->getField()->setValue($fieldAccess->getThis(), 'some value'); |
The inspection completed: 1 updated code elements |
@lisachenko any plans to release this feature? :) |
3.0.0-RC1 is ready to test, if it is ok, then 3.0.0 will be released soon |
This PR introduces an ability to intercept access to private properties in classes. We use closure binding in generated proxy child class and bind it to the parent scope so we gain a control over private properties of the class as well.
Here is an example of generated constructor for the
Demo\Example\PropertyDemo
proxy class:As we store references to properties from given original object instance, we can read and write them via aspects without additional code logic.
Feature was requested in #411 by @jakzal