-
-
Save kastner/545 to your computer and use it in GitHub Desktop.
Joe's meta-programing for testing private stuff in PHP
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 | |
class Foo | |
{ | |
protected $user = null; | |
public function __construct($user) | |
{ | |
$this->user = $user; | |
} | |
protected function test($name) | |
{ | |
return "Hello $name!\n"; | |
} | |
} | |
function getProxy($class, array $args = array()) | |
{ | |
if (!class_exists($class)) { | |
throw Exception('Class does not exist'); | |
} | |
$code = <<< CODE | |
class Proxy_$class extends $class | |
{ | |
public function __get(\$var) | |
{ | |
static \$ref = null; | |
if (is_null(\$ref)) { | |
\$ref = new ReflectionClass('$class'); | |
} | |
\$parts = explode('_', \$var); | |
\$type = array_shift(\$parts); | |
\$var = implode('_', \$parts); | |
\$prop = \$ref->getProperty(\$var); | |
\$func = 'is' . ucfirst(\$type); | |
if (!\$prop->\$func()) { | |
throw Exception(\$var . ' is not ' . \$type); | |
} | |
return \$this->\$var; | |
} | |
public function __call(\$function, array \$args = array()) | |
{ | |
static \$ref = null; | |
if (is_null(\$ref)) { | |
\$ref = new ReflectionClass('$class'); | |
} | |
\$parts = explode('_', \$function); | |
\$type = array_shift(\$parts); | |
\$function = implode('_', \$parts); | |
\$method = \$ref->getMethod(\$function); | |
\$func = 'is' . ucfirst(\$type); | |
if (!\$method->\$func()) { | |
throw Exception(\$function . ' is not ' . \$type); | |
} | |
return call_user_func_array(array(\$this, \$function), \$args); | |
} | |
} | |
CODE; | |
eval($code); | |
$ref = new ReflectionClass('Proxy_' . $class); | |
$obj = $ref->newInstanceArgs($args); | |
return $obj; | |
} | |
$obj = getProxy('Foo', array('joestump')); | |
echo $obj->protected_user . "\n"; | |
echo $obj->protected_test($obj->protected_user) . "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment