Skip to content

Instantly share code, notes, and snippets.

@waterada
Created October 23, 2012 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waterada/3939215 to your computer and use it in GitHub Desktop.
Save waterada/3939215 to your computer and use it in GitHub Desktop.
Class easier to access to any protected methods for UnitTest.
<?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