/
AopProxyService.php
69 lines (59 loc) · 2 KB
/
AopProxyService.php
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
<?php
namespace SilverStripe\Core\Injector;
/**
* A class that proxies another, allowing various functionality to be
* injected.
*/
class AopProxyService
{
public $beforeCall = [];
public $afterCall = [];
public $proxied;
/**
* Because we don't know exactly how the proxied class is usually called,
* provide a default constructor
*/
public function __construct()
{
}
public function __call($method, $args)
{
if (method_exists($this->proxied, $method ?? '')) {
$continue = true;
$result = null;
if (isset($this->beforeCall[$method])) {
$methods = $this->beforeCall[$method];
if (!is_array($methods)) {
$methods = [$methods];
}
foreach ($methods as $handler) {
$alternateReturn = null;
$proceed = $handler->beforeCall($this->proxied, $method, $args, $alternateReturn);
if ($proceed === false) {
$continue = false;
// if something is set in, use it
if ($alternateReturn) {
$result = $alternateReturn;
}
}
}
}
if ($continue) {
$result = call_user_func_array([$this->proxied, $method], $args ?? []);
if (isset($this->afterCall[$method])) {
$methods = $this->afterCall[$method];
if (!is_array($methods)) {
$methods = [$methods];
}
foreach ($methods as $handler) {
$return = $handler->afterCall($this->proxied, $method, $args, $result);
if (!is_null($return)) {
$result = $return;
}
}
}
}
return $result;
}
}
}