-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scope.php
75 lines (63 loc) · 1.65 KB
/
Scope.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
70
71
72
73
74
75
<?php
namespace ScopeGuard;
class Scope
{
private $success = false;
private $failureHandlers = [];
private $successHandlers = [];
private $exitHandlers = [];
public static function exit(callable $onExit): self {
$scope = new Scope();
$scope->onExit($onExit);
return $scope;
}
public function markSuccessful() {
$this->success = true;
}
public function onExit(callable $onExit) {
$this->exitHandlers[] = $onExit;
}
public function onFailure(callable $onFailure) {
$this->failureHandlers[] = $onFailure;
}
public function onSuccess(callable $onSuccess) {
$this->successHandlers[] = $onSuccess;
}
public function executeSuccessHandlers()
{
foreach ($this->successHandlers as $handler) {
$handler();
}
}
/**
* We would like to pass the current exception to the handler
* but the engine does not currently support this
*/
public function executeFailureHandlers()
{
foreach ($this->failureHandlers as $handler) {
$handler();
}
}
public function executeExitHandlers()
{
foreach ($this->exitHandlers as $handler) {
$handler();
}
}
/**
* The most logical sequence seems to do onExit handlers last,
* since they are usually for cleanup.
*
* Should we catch exceptions?
*/
public function __destruct()
{
if ($this->success) {
$this->executeSuccessHandlers();
} else {
$this->executeFailureHandlers();
}
$this->executeExitHandlers();
}
}