Completed
Push — master ( 1e0a7f...79d97e )
by Korotkov
01:54 queued 11s
created

Chain::execute()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 17
rs 9.6111
cc 5
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @author  : Jagepard <[email protected]>
7
 * @license https://mit-license.org/ MIT
8
 */
9
10
namespace Behavioral\ChainOfResponsibility;
11
12
class Chain implements ChainInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    private $chain = [];
18
19
    /**
20
     * @param  HandlerInterface  $handler
21
     */
22
    public function addToChain(HandlerInterface $handler): void
23
    {
24
        $handlerName = get_class($handler);
25
26
        if (array_key_exists($handlerName, $this->chain)) {
27
            throw new \InvalidArgumentException('Handler already exists');
28
        }
29
30
        $this->chain[$handlerName] = $handler;
31
    }
32
33
    /**
34
     * @param  string  $handlerName
35
     * @throws \Exception
36
     */
37
    public function execute(string $handlerName): void
38
    {
39
        if (!count($this->chain)) {
40
            throw new \Exception('The chain is empty');
41
        }
42
43
        if (array_key_exists($handlerName, $this->chain)) {
44
            foreach ($this->chain as $handler) {
45
                $handler->execute();
46
47
                if (get_class($handler) === $handlerName) {
48
                    return;
49
                }
50
            }
51
        }
52
53
        throw new \InvalidArgumentException('Handler does not exist in the chain');
54
    }
55
}
56