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

AbstractHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 4
Metric Value
wmc 6
eloc 16
c 6
b 0
f 4
dl 0
loc 53
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setNext() 0 4 1
A execute() 0 24 5
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