Created
February 5, 2022 20:54
-
-
Save juampi92/4eec2a0ed225973222b9154a6ca7c671 to your computer and use it in GitHub Desktop.
Testing private methods 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 | |
if (!function_exists('private_access')) { | |
function private_access(object $object) | |
{ | |
return new PrivateAccess($object); | |
} | |
} |
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 | |
namespace Tests\Support; | |
use ReflectionClass; | |
use ReflectionException; | |
use ReflectionObject; | |
class PrivateAccess | |
{ | |
public function __construct( | |
private object $object, | |
) { | |
} | |
/** | |
* @throws ReflectionException | |
*/ | |
public function __call(string $methodName, array $arguments): mixed | |
{ | |
$class = new ReflectionClass($this->object); | |
$method = $class->getMethod($methodName); | |
$method->setAccessible(true); | |
return $method->invokeArgs($this->object, $arguments); | |
} | |
/** | |
* @throws ReflectionException | |
*/ | |
public function __get(string $name): mixed | |
{ | |
$class = new ReflectionObject($this->object); | |
$property = $class->getProperty($name); | |
$property->setAccessible(true); | |
return $property->getValue($this->object); | |
} | |
/** | |
* @throws ReflectionException | |
*/ | |
public function __set(string $name, mixed $value): void | |
{ | |
$reflection = new ReflectionClass($this->object); | |
$reflectionProperty = $reflection->getProperty($name); | |
$reflectionProperty->setAccessible(true); | |
$reflectionProperty->setValue($this->object, $value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment