Created
October 23, 2012 14:52
-
-
Save waterada/3939215 to your computer and use it in GitHub Desktop.
Class easier to access to any protected methods for UnitTest.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* private/protected なメソッド/プロパティに | |
* アクセスできるようにするラッパーオブジェクト。 | |
*/ | |
class ProtectBreakMagic { | |
public $object; | |
private $ref; | |
/** | |
* コンストラクタ。 | |
* @param object $object | |
*/ | |
public function __construct($object) { | |
$this->object = $object; | |
$this->ref = new ReflectionClass(get_class($this->object)); | |
} | |
/** | |
* メソッドの呼び出し | |
*/ | |
public function __call($method, $arguments) { | |
$methodObj = $this->ref->getMethod($method); | |
$methodObj->setAccessible(true); | |
return $methodObj->invokeArgs($this->object, $arguments); | |
} | |
/** | |
* パラメータ取得 | |
*/ | |
public function __get($name) { | |
if ( $this->ref->hasProperty($name) ) { | |
$propObj = $this->ref->getProperty($name); | |
$propObj->setAccessible(true); | |
return $propObj->getValue($this->object); | |
} else { | |
return null; | |
} | |
} | |
/** | |
* パラメータ書き換え | |
*/ | |
public function __set($name, $value) { | |
if ( $this->ref->hasProperty($name) ) { | |
//存在するならアクセス権を広げて設定 | |
$propObj = $this->ref->getProperty($name); | |
$propObj->setAccessible(true); | |
$propObj->setValue($this->object, $value); | |
} else { | |
//存在しなければ新規に設定 | |
$this->object->$name = $value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment