1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT |
5
|
|
|
* @link https://github.com/nicoSWD |
6
|
|
|
* @author Nicolas Oelgart <[email protected]> |
7
|
|
|
*/ |
8
|
|
|
namespace nicoSWD\Rule\TokenStream; |
9
|
|
|
|
10
|
|
|
use Closure; |
11
|
|
|
use nicoSWD\Rule\Grammar\CallableUserFunctionInterface; |
12
|
|
|
use nicoSWD\Rule\TokenStream\Token\BaseToken; |
13
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenFactory; |
14
|
|
|
|
15
|
|
|
final class CallableUserMethod implements CallableUserFunctionInterface |
16
|
|
|
{ |
17
|
|
|
/** @var TokenFactory */ |
18
|
|
|
private $tokenFactory; |
19
|
|
|
/** @var Closure */ |
20
|
|
|
private $callable; |
21
|
|
|
/** @var string[] */ |
22
|
|
|
private $methodPrefixes = ['get', 'is', '', 'get_', 'is_']; |
23
|
|
|
|
24
|
18 |
|
public function __construct(BaseToken $token, TokenFactory $tokenFactory, string $methodName) |
25
|
|
|
{ |
26
|
18 |
|
$this->tokenFactory = $tokenFactory; |
27
|
18 |
|
$this->callable = $this->getCallable($token, $methodName); |
28
|
16 |
|
} |
29
|
|
|
|
30
|
18 |
|
private function getCallable(BaseToken $token, string $methodName): Closure |
31
|
|
|
{ |
32
|
18 |
|
$object = $token->getValue(); |
33
|
|
|
|
34
|
18 |
|
if (property_exists($object, $methodName)) { |
35
|
4 |
|
return function () use ($object, $methodName) { |
36
|
4 |
|
return $object->{$methodName}; |
37
|
4 |
|
}; |
38
|
|
|
} |
39
|
|
|
|
40
|
14 |
|
$method = [$object]; |
41
|
14 |
|
$index = 0; |
42
|
|
|
|
43
|
|
|
do { |
44
|
14 |
|
if (!isset($this->methodPrefixes[$index])) { |
45
|
2 |
|
throw new Exception\UndefinedMethodException(); |
46
|
|
|
} |
47
|
|
|
|
48
|
14 |
|
$method[1] = $this->methodPrefixes[$index++] . $methodName; |
49
|
14 |
|
} while (!is_callable($method)); |
50
|
|
|
|
51
|
12 |
|
return function (BaseToken $param = null) use ($method) { |
52
|
12 |
|
return $method($param ? $param->getValue() : null); |
53
|
12 |
|
}; |
54
|
|
|
} |
55
|
|
|
|
56
|
16 |
|
public function call(BaseToken $param = null): BaseToken |
57
|
|
|
{ |
58
|
16 |
|
$callable = $this->callable; |
59
|
|
|
|
60
|
16 |
|
return $this->tokenFactory->createFromPHPType( |
61
|
16 |
|
$callable($param) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|