1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace AlecRabbit\Helpers\Objects; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class Picklock |
7
|
|
|
* |
8
|
|
|
* @link https://gitlab.com/m0rtis/picklock |
9
|
|
|
* @license Apache License 2.0 |
10
|
|
|
* @author Anton Fomichev aka m0rtis - [email protected] |
11
|
|
|
* |
12
|
|
|
* @package AlecRabbit\Helpers\Objects |
13
|
|
|
* @author AlecRabbit |
14
|
|
|
* |
15
|
|
|
*/ |
16
|
|
|
final class Picklock |
17
|
|
|
{ |
18
|
|
|
public const EXCEPTION_TEMPLATE = 'Class [%s] does not have `%s` %s'; |
19
|
|
|
public const METHOD = 'method'; |
20
|
|
|
public const PROPERTY = 'property'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Calls method $methodName of object $object using arguments ...$args. |
24
|
|
|
* |
25
|
|
|
* @psalm-suppress InvalidScope |
26
|
|
|
* |
27
|
|
|
* @param object $object |
28
|
|
|
* @param string $methodName |
29
|
|
|
* @param mixed ...$args |
30
|
|
|
* @return mixed |
31
|
|
|
*/ |
32
|
1 |
|
public static function callMethod(object $object, string $methodName, ...$args) |
33
|
|
|
{ |
34
|
|
|
$closure = |
35
|
|
|
/** |
36
|
|
|
* @param string $methodName |
37
|
|
|
* @param array $args |
38
|
|
|
* @return mixed |
39
|
|
|
*/ |
40
|
|
|
function (string $methodName, ...$args) { |
41
|
1 |
|
if (\method_exists($this, $methodName)) { |
|
|
|
|
42
|
1 |
|
return $this->$methodName(...$args); |
43
|
|
|
} |
44
|
1 |
|
throw new \RuntimeException( |
45
|
1 |
|
sprintf( |
46
|
1 |
|
Picklock::EXCEPTION_TEMPLATE, |
47
|
1 |
|
\get_class($this), |
48
|
1 |
|
$methodName, |
49
|
1 |
|
Picklock::METHOD |
50
|
|
|
) |
51
|
|
|
); |
52
|
1 |
|
}; |
53
|
|
|
return |
54
|
1 |
|
$closure->call($object, $methodName, ...$args); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @psalm-suppress InvalidScope |
59
|
|
|
* |
60
|
|
|
* @param object $object |
61
|
|
|
* @param string $propName |
62
|
|
|
* @return mixed |
63
|
|
|
*/ |
64
|
1 |
|
public static function getValue(object $object, string $propName) |
65
|
|
|
{ |
66
|
|
|
$closure = |
67
|
|
|
/** |
68
|
|
|
* @return mixed |
69
|
|
|
*/ |
70
|
|
|
function () use ($propName) { |
71
|
1 |
|
if (\property_exists($this, $propName)) { |
|
|
|
|
72
|
1 |
|
return $this->$propName; |
73
|
|
|
} |
74
|
1 |
|
throw new \RuntimeException( |
75
|
1 |
|
sprintf( |
76
|
1 |
|
Picklock::EXCEPTION_TEMPLATE, |
77
|
1 |
|
\get_class($this), |
78
|
1 |
|
$propName, |
79
|
1 |
|
Picklock::PROPERTY |
80
|
|
|
) |
81
|
|
|
); |
82
|
1 |
|
}; |
83
|
|
|
return |
84
|
1 |
|
$closure->bindTo($object, $object)(); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|