Skip to content

Instantly share code, notes, and snippets.

@alOneh
Created December 16, 2019 12:25
Show Gist options
  • Save alOneh/b9a17c1b9cdf96a6df916b12fd7756cd to your computer and use it in GitHub Desktop.
Save alOneh/b9a17c1b9cdf96a6df916b12fd7756cd to your computer and use it in GitHub Desktop.
<?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