forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionHelper.php
More file actions
99 lines (87 loc) · 2.47 KB
/
ReflectionHelper.php
File metadata and controls
99 lines (87 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Test;
use Closure;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionObject;
use ReflectionProperty;
/**
* Testing helper.
*/
trait ReflectionHelper
{
/**
* Find a private method invoker.
*
* @param object|string $obj object or class name
* @param string $method method name
*
* @return Closure(mixed ...$args): mixed
*
* @throws ReflectionException
*/
public static function getPrivateMethodInvoker($obj, $method)
{
$refMethod = new ReflectionMethod($obj, $method);
$obj = (gettype($obj) === 'object') ? $obj : null;
return static fn (...$args): mixed => $refMethod->invokeArgs($obj, $args);
}
/**
* Find an accessible property.
*
* @param object|string $obj
* @param string $property
*
* @return ReflectionProperty
*
* @throws ReflectionException
*/
private static function getAccessibleRefProperty($obj, $property)
{
$refClass = is_object($obj) ? new ReflectionObject($obj) : new ReflectionClass($obj);
return $refClass->getProperty($property);
}
/**
* Set a private property.
*
* @param object|string $obj object or class name
* @param string $property property name
* @param mixed $value value
*
* @throws ReflectionException
*/
public static function setPrivateProperty($obj, $property, $value): void
{
$refProperty = self::getAccessibleRefProperty($obj, $property);
if (is_object($obj)) {
$refProperty->setValue($obj, $value);
} else {
$refProperty->setValue(null, $value);
}
}
/**
* Retrieve a private property.
*
* @param object|string $obj object or class name
* @param string $property property name
*
* @return mixed
*
* @throws ReflectionException
*/
public static function getPrivateProperty($obj, $property)
{
$refProperty = self::getAccessibleRefProperty($obj, $property);
return is_string($obj) ? $refProperty->getValue() : $refProperty->getValue($obj);
}
}