6 * The "Invasive" helper makes it a bit easier to write unit-tests which
7 * touch upon private or protected members.
14 * Call a private/protected method.
16 * This is only intended for unit-testing.
18 * @param array $callable
19 * Ex: [$myObject, 'myPrivateMethod']
20 * Ex: ['MyClass', 'myPrivateStaticMethod']
22 * Ordered list of arguments.
25 public static function call($callable, $args = []) {
26 list ($class, $object, $member) = self
::parseRef($callable);
27 $reflection = new \
ReflectionMethod($class, $member);
28 $reflection->setAccessible(TRUE);
29 return $reflection->invokeArgs($object, $args);
33 * Get the content of a private/protected method.
35 * This is only intended for unit-testing.
38 * A reference to class+property.
39 * Ex: [$myObject, 'myPrivateField']
40 * Ex: ['MyClass', 'myPrivateStaticField']
43 public static function get($ref) {
44 list ($class, $object, $member) = self
::parseRef($ref);
45 $reflection = new \
ReflectionProperty($class, $member);
46 $reflection->setAccessible(TRUE);
47 return $reflection->getValue($object);
51 * Get the content of a private/protected method.
53 * This is only intended for unit-testing.
56 * A reference to class+property.
57 * Ex: [$myObject, 'myPrivateField']
58 * Ex: ['MyClass', 'myPrivateStaticField']
62 public static function set($ref, $value) {
63 list ($class, $object, $member) = self
::parseRef($ref);
64 $reflection = new \
ReflectionProperty($class, $member);
65 $reflection->setAccessible(TRUE);
66 $reflection->setValue($object, $value);
70 * @param array $callable
71 * Ex: [$myObject, 'myPrivateMember']
72 * Ex: ['MyClass', 'myPrivateStaticMember']
74 * Ordered array of [string $class, object? $object, string $memberName].
76 private static function parseRef($callable) {
77 if (is_string($callable)) {
78 list ($class, $member) = explode('::', $callable);
79 return [$class, NULL, $member];
81 elseif (is_string($callable[0])) {
82 return [$callable[0], NULL, $callable[1]];
84 elseif (is_object($callable[0])) {
85 return [get_class($callable[0]), $callable[0], $callable[1]];
88 throw new \
RuntimeException("Cannot parse reference to private member");