1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace veejay\jsonrpc\tests; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use ReflectionClass; |
7
|
|
|
|
8
|
|
|
final class ProtectedHelper |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Get protected property. |
12
|
|
|
* @param string|object $object |
13
|
|
|
* @param string $property |
14
|
|
|
* @return mixed|bool |
15
|
|
|
*/ |
16
|
|
|
public static function getProperty($object, string $property) |
17
|
|
|
{ |
18
|
|
|
$reflection = new ReflectionClass($object); |
19
|
|
|
if (!$reflection->hasProperty($property)) return false; |
20
|
|
|
$property = $reflection->getProperty($property); |
21
|
|
|
$property->setAccessible(true); |
22
|
|
|
return $property->getValue($object); |
|
|
|
|
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Set protected property. |
27
|
|
|
* @param string|object $object |
28
|
|
|
* @param string $property |
29
|
|
|
* @param mixed $value |
30
|
|
|
* @return void |
31
|
|
|
*/ |
32
|
|
|
public static function setProperty($object, string $property, $value) |
33
|
|
|
{ |
34
|
|
|
$reflection = new ReflectionClass($object); |
35
|
|
|
$property = $reflection->getProperty($property); |
36
|
|
|
$property->setAccessible(true); |
37
|
|
|
if ($property->isStatic()) { |
38
|
|
|
$property->setValue($value); |
39
|
|
|
} else { |
40
|
|
|
$property->setValue($object, $value); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Call protected method. |
46
|
|
|
* @param string|object $object |
47
|
|
|
* @param string $methodName |
48
|
|
|
* @param array $params |
49
|
|
|
* @return mixed|bool |
50
|
|
|
*/ |
51
|
|
|
public static function callMethod($object, string $methodName, array $params = []) |
52
|
|
|
{ |
53
|
|
|
$reflection = new ReflectionClass(get_class($object)); |
|
|
|
|
54
|
|
|
if (!$reflection->hasMethod($methodName)) return false; |
55
|
|
|
$method = $reflection->getMethod($methodName); |
56
|
|
|
$method->setAccessible(true); |
57
|
|
|
return $method->invokeArgs($object, $params); |
|
|
|
|
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Catch exception and return the code. |
62
|
|
|
* @param callable $callback |
63
|
|
|
* @return int |
64
|
|
|
*/ |
65
|
|
|
public static function catchExceptionCode(callable $callback): int |
66
|
|
|
{ |
67
|
|
|
try { |
68
|
|
|
$callback(); |
69
|
|
|
return 0; |
70
|
|
|
} catch (Exception $e) { |
71
|
|
|
return $e->getCode(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|