Passed
Push — master ( a0e443...4eef22 )
by Korotkov
01:42 queued 14s
created

AbstractHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 3
Metric Value
wmc 7
eloc 17
c 5
b 0
f 3
dl 0
loc 55
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setNext() 0 4 1
A getName() 0 3 1
A execute() 0 23 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
     * @param string $request
20
     * @param bool $allInChain
21
     */
22
    public function execute(string $request, bool $allInChain = false): void
23
    {
24
        if ($allInChain) {
25
            printf("%s %s\n", get_called_class(), "has handle a request");
26
27
            if ($request === $this->getName()) {
28
                return;
29
            }
30
        } else {
31
            // In case of compliance, the code is executed
32
            if ($request === $this->getName()) {
33
                printf("%s %s\n", get_called_class(), "has handle a request");
34
                return;
35
            }
36
        }
37
38
39
        if (!isset($this->nextHandler)) {
40
            throw new \InvalidArgumentException($request . " does not exist in the chain");
41
        }
42
43
        // Passed to the next handler
44
        $this->nextHandler->execute($request, $allInChain);
45
    }
46
47
    /**
48
     * Adds the next handler to the chain
49
     *
50
     * @param AbstractHandler $handler
51
     * @return AbstractHandler
52
     */
53
    public function setNext(AbstractHandler $handler): AbstractHandler
54
    {
55
        $this->nextHandler = $handler;
56
        return $handler;
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    public function getName(): string
63
    {
64
        return $this->name;
65
    }
66
}
67