|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @author : Jagepard <[email protected]> |
|
5
|
|
|
* @license https://mit-license.org/ MIT |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace Behavioral\ChainOfResponsibility; |
|
9
|
|
|
|
|
10
|
|
|
abstract class AbstractHandler implements ChainInterface |
|
11
|
|
|
{ |
|
12
|
|
|
protected AbstractHandler $nextHandler; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* If the condition matches, code is executed; |
|
16
|
|
|
* if not, then it is passed along the chain to the next handler |
|
17
|
|
|
* |
|
18
|
|
|
* @param string $request |
|
19
|
|
|
*/ |
|
20
|
|
|
public function execute(string $request): void |
|
21
|
|
|
{ |
|
22
|
|
|
// In case of compliance, the code is executed |
|
23
|
|
|
if ($request === get_called_class()) { |
|
24
|
|
|
printf("%s %s\n", get_called_class(), "has handle a request"); |
|
25
|
|
|
return; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
if (!isset($this->nextHandler)) { |
|
29
|
|
|
throw new \InvalidArgumentException($request . " does not exist in the chain"); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
// Passed to the next handler |
|
33
|
|
|
$this->nextHandler->execute($request); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function executeAllInChainBeforeRequest(string $request): void |
|
37
|
|
|
{ |
|
38
|
|
|
printf("%s %s\n", get_called_class(), "has handle a request"); |
|
39
|
|
|
|
|
40
|
|
|
if ($request === get_called_class()) { |
|
41
|
|
|
return; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (!isset($this->nextHandler)) { |
|
45
|
|
|
throw new \InvalidArgumentException($request . " does not exist in the chain"); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
// Passed to the next handler |
|
49
|
|
|
$this->nextHandler->executeAllInChainBeforeRequest($request); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Adds the next handler to the chain |
|
54
|
|
|
* |
|
55
|
|
|
* @param AbstractHandler $handler |
|
56
|
|
|
* @return AbstractHandler |
|
57
|
|
|
*/ |
|
58
|
|
|
public function setNext(AbstractHandler $handler): AbstractHandler |
|
59
|
|
|
{ |
|
60
|
|
|
$this->nextHandler = $handler; |
|
61
|
|
|
return $handler; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|