Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / tests / phpunit / includes / TestingAccessWrapper.php
blob63d897198b6da804127e377533bb6ec6a9749f5a
1 <?php
2 /**
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();
14 * TODO:
15 * - Provide access to static methods and properties.
16 * - Organize other helper classes in tests/testHelpers.inc into a directory.
18 class TestingAccessWrapper {
19 public $object;
21 /**
22 * Return the same object, without access restrictions.
24 public static function newFromObject( $object ) {
25 $wrapper = new TestingAccessWrapper();
26 $wrapper->object = $object;
27 return $wrapper;
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 );
37 /**
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 );
43 try {
44 return $classReflection->getProperty( $name );
45 } catch ( ReflectionException $ex ) {
46 while ( true ) {
47 $classReflection = $classReflection->getParentClass();
48 if ( !$classReflection ) {
49 throw $ex;
51 try {
52 $propertyReflection = $classReflection->getProperty( $name );
53 } catch ( ReflectionException $ex2 ) {
54 continue;
56 if ( $propertyReflection->isPrivate() ) {
57 return $propertyReflection;
58 } else {
59 throw $ex;
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 );