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

Chain   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 13
Bugs 0 Features 1
Metric Value
wmc 7
eloc 14
c 13
b 0
f 1
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A addToChain() 0 9 2
A execute() 0 17 5
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