Completed
Pull Request — master (#51)
by Korotkov
07:55
created

AbstractHandler::execute()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 3
Metric Value
eloc 11
c 3
b 0
f 3
dl 0
loc 24
rs 9.6111
cc 5
nc 6
nop 2
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 string $name;
13
    protected AbstractHandler $nextHandler;
14
15
    /**
16
     * If the condition matches, code is executed;
17
     * if not, then it is passed along the chain to the next handler
18
     * -------------------------------------------------------------
19
     * Если условие совпадает, код выполняется;
20
     * Если нет, то он передается по цепочке следующему обработчику
21
     *
22
     * @param string $request
23
     * @param bool $allInChain
24
     */
25
    public function execute(string $request, bool $allInChain = false): void
26
    {
27
        if ($allInChain) {
28
            printf("%s %s\n", get_called_class(), "has handle a request");
29
30
            if ($request === $this->name) {
31
                return;
32
            }
33
        } else {
34
            // In case of compliance, the code is executed
35
            // В случае соответствия код выполняется
36
            if ($request === $this->name) {
37
                printf("%s %s\n", get_called_class(), "has handle a request");
38
                return;
39
            }
40
        }
41
42
        if (!isset($this->nextHandler)) {
43
            throw new \InvalidArgumentException($request . " does not exist in the chain");
44
        }
45
46
        // Passed to the next handler
47
        // Передано следующему обработчику
48
        $this->nextHandler->execute($request, $allInChain);
49
    }
50
51
    /**
52
     * Adds the next handler to the chain
53
     * ----------------------------------
54
     * Добавляет следующий обработчик в цепочку
55
     *
56
     * @param AbstractHandler $handler
57
     * @return AbstractHandler
58
     */
59
    public function setNext(AbstractHandler $handler): AbstractHandler
60
    {
61
        $this->nextHandler = $handler;
62
        return $handler;
63
    }
64
}
65