1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yiisoft\Proxy; |
4
|
|
|
|
5
|
|
|
abstract class ObjectProxy |
6
|
|
|
{ |
7
|
|
|
private object $instance; |
8
|
|
|
|
9
|
|
|
private ?object $currentError = null; |
10
|
|
|
|
11
|
|
|
public function __construct(object $instance) |
12
|
|
|
{ |
13
|
|
|
$this->instance = $instance; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
protected function call(string $methodName, array $arguments) |
17
|
|
|
{ |
18
|
|
|
$this->resetCurrentError(); |
19
|
|
|
try { |
20
|
|
|
$result = null; |
21
|
|
|
$timeStart = microtime(true); |
22
|
|
|
$result = $this->callInternal($methodName, $arguments); |
23
|
|
|
} catch (\Exception $e) { |
24
|
|
|
$this->repeatError($e); |
25
|
|
|
} finally { |
26
|
|
|
$result = $this->executeMethodProxy($methodName, $arguments, $result, $timeStart); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $this->processResult($result); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
abstract protected function executeMethodProxy(string $methodName, array $arguments, $result, float $timeStart); |
33
|
|
|
|
34
|
|
|
protected function getCurrentError(): ?object |
35
|
|
|
{ |
36
|
|
|
return $this->currentError; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function getCurrentResultStatus(): string |
40
|
|
|
{ |
41
|
|
|
return $this->currentError === null ? 'success' : 'failed'; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function getNewStaticInstance(object $instance): self |
45
|
|
|
{ |
46
|
|
|
return new static($instance); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function getInstance(): object |
50
|
|
|
{ |
51
|
|
|
return $this->instance; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function callInternal(string $methodName, array $arguments) |
55
|
|
|
{ |
56
|
|
|
return $this->instance->$methodName(...$arguments); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function processResult($result) |
60
|
|
|
{ |
61
|
|
|
if (is_object($result) && get_class($result) === get_class($this->instance)) { |
62
|
|
|
$result = $this->getNewStaticInstance($result); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $result; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function repeatError(object $error): void |
69
|
|
|
{ |
70
|
|
|
$this->currentError = $error; |
71
|
|
|
$errorClass = get_class($error); |
72
|
|
|
throw new $errorClass($error->getMessage()); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function resetCurrentError(): void |
76
|
|
|
{ |
77
|
|
|
$this->currentError = null; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|