3 * Circumvent access restrictions on object internals
5 * This can be helpful for writing tests that can probe object internals,
6 * without having to modify the class under test to accomodate.
8 * Wrap an object with private methods as follows:
9 * $title = TestingAccessWrapper::newFromObject( Title::newFromDBkey( $key ) );
11 * You can access private and protected instance methods and variables:
12 * $formatter = $title->getTitleFormatter();
15 * - Provide access to static methods and properties.
16 * - Organize other helper classes in tests/testHelpers.inc into a directory.
18 class TestingAccessWrapper
{
22 * Return the same object, without access restrictions.
24 public static function newFromObject( $object ) {
25 $wrapper = new TestingAccessWrapper();
26 $wrapper->object = $object;
30 public function __call( $method, $args ) {
31 $classReflection = new ReflectionClass( $this->object );
32 $methodReflection = $classReflection->getMethod( $method );
33 $methodReflection->setAccessible( true );
34 return $methodReflection->invokeArgs( $this->object, $args );
38 * ReflectionClass::getProperty() fails if the private property is defined
39 * in a parent class. This works more like ReflectionClass::getMethod().
41 private function getProperty( $name ) {
42 $classReflection = new ReflectionClass( $this->object );
44 return $classReflection->getProperty( $name );
45 } catch ( ReflectionException
$ex ) {
47 $classReflection = $classReflection->getParentClass();
48 if ( !$classReflection ) {
52 $propertyReflection = $classReflection->getProperty( $name );
53 } catch ( ReflectionException
$ex2 ) {
56 if ( $propertyReflection->isPrivate() ) {
57 return $propertyReflection;
65 public function __set( $name, $value ) {
66 $propertyReflection = $this->getProperty( $name );
67 $propertyReflection->setAccessible( true );
68 $propertyReflection->setValue( $this->object, $value );
71 public function __get( $name ) {
72 $propertyReflection = $this->getProperty( $name );
73 $propertyReflection->setAccessible( true );
74 return $propertyReflection->getValue( $this->object );