Last active
February 10, 2017 14:29
-
-
Save djsipe/c9844c2a29ad34f92e75b65690f03a38 to your computer and use it in GitHub Desktop.
PHP Trait for Testing Protected Methods and Properties
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 | |
/** | |
* Trait to expose protected methods and properties. | |
*/ | |
trait TestProtectedTrait | |
{ | |
/** | |
* Call protected/private method of a class. | |
* | |
* @param object|string $object Instantiated object that we will run method on or the class name. | |
* @param string $methodName Method name to call | |
* @param array $parameters Array of parameters to pass into method. | |
* @param bool $static Is a static method? | |
* | |
* @return mixed Method return. | |
*/ | |
public function callProtectedMethod($object, $methodName, array $parameters = array(), $static = false) | |
{ | |
$reflection = new \ReflectionClass($object); | |
$method = $reflection->getMethod($methodName); | |
$method->setAccessible(true); | |
if ($static) { | |
$object = null; | |
} | |
return $method->invokeArgs($object, $parameters); | |
} | |
/** | |
* Get protected/private property value | |
* | |
* @param object|string $object | |
* @param string $propertyName | |
* @return mixed | |
*/ | |
protected function getProtectedProperty($object, $propertyName) | |
{ | |
$reflection = new \ReflectionClass($object); | |
$property = $reflection->getProperty($propertyName); | |
$property->setAccessible(true); | |
return $property->getValue($object); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment