Created
December 16, 2019 12:25
-
-
Save alOneh/b9a17c1b9cdf96a6df916b12fd7756cd to your computer and use it in GitHub Desktop.
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 | |
// tests/App/ReflectionTrait.php | |
namespace App\Tests; | |
trait ReflectionTrait | |
{ | |
/** | |
* @param $object | |
* @param $methodName | |
* @param array $parameters | |
* @return mixed | |
*/ | |
public function invokeMethod(&$object, $methodName, array $parameters = []) | |
{ | |
$reflection = $this->createReflection($object); | |
$method = $reflection->getMethod($methodName); | |
$method->setAccessible(true); | |
return $method->invokeArgs($object, $parameters); | |
} | |
/** | |
* @param $class | |
* @return \ReflectionClass | |
* @throws \ReflectionException | |
*/ | |
protected function createReflection($class) | |
{ | |
if (is_object($class)) { | |
$class = get_class($class); | |
} | |
return new \ReflectionClass($class); | |
} | |
/** | |
* @param $object | |
* @param $propertyName | |
* @return mixed | |
*/ | |
public function getProperty(&$object, $propertyName) | |
{ | |
$reflection = $this->createReflection($object); | |
$property = $reflection->getProperty($propertyName); | |
$property->setAccessible(true); | |
return $property->getValue($object); | |
} | |
/** | |
* @param $object | |
* @param $propertyName | |
* @param $value | |
*/ | |
public function setProperty(&$object, $propertyName, $value) | |
{ | |
$reflection = $this->createReflection($object); | |
$property = $reflection->getProperty($propertyName); | |
$property->setAccessible(true); | |
$property->setValue($object, $value); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment