LocalisationCache: try harder to use LCStoreCDB
[lhc/web/wiklou.git] / tests / phpunit / includes / TestingAccessWrapper.php
1 <?php
2 /**
3 * Circumvent access restrictions on object internals
4 *
5 * This can be helpful for writing tests that can probe object internals,
6 * without having to modify the class under test to accomodate.
7 *
8 * Wrap an object with private methods as follows:
9 * $title = TestingAccessWrapper::newFromObject( Title::newFromDBkey( $key ) );
10 *
11 * You can access private and protected instance methods and variables:
12 * $formatter = $title->getTitleFormatter();
13 *
14 * TODO:
15 * - Provide access to static methods and properties.
16 * - Organize other helper classes in tests/testHelpers.inc into a directory.
17 */
18 class TestingAccessWrapper {
19 public $object;
20
21 /**
22 * Return the same object, without access restrictions.
23 */
24 public static function newFromObject( $object ) {
25 $wrapper = new TestingAccessWrapper();
26 $wrapper->object = $object;
27 return $wrapper;
28 }
29
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 );
35 }
36
37 /**
38 * ReflectionClass::getProperty() fails if the private property is defined
39 * in a parent class. This works more like ReflectionClass::getMethod().
40 */
41 private function getProperty( $name ) {
42 $classReflection = new ReflectionClass( $this->object );
43 try {
44 return $classReflection->getProperty( $name );
45 } catch ( ReflectionException $ex ) {
46 while ( true ) {
47 $classReflection = $classReflection->getParentClass();
48 if ( !$classReflection ) {
49 throw $ex;
50 }
51 try {
52 $propertyReflection = $classReflection->getProperty( $name );
53 } catch ( ReflectionException $ex2 ) {
54 continue;
55 }
56 if ( $propertyReflection->isPrivate() ) {
57 return $propertyReflection;
58 } else {
59 throw $ex;
60 }
61 }
62 }
63 }
64
65 public function __set( $name, $value ) {
66 $propertyReflection = $this->getProperty( $name );
67 $propertyReflection->setAccessible( true );
68 $propertyReflection->setValue( $this->object, $value );
69 }
70
71 public function __get( $name ) {
72 $propertyReflection = $this->getProperty( $name );
73 $propertyReflection->setAccessible( true );
74 return $propertyReflection->getValue( $this->object );
75 }
76 }