Completed
Push — master ( 7c00aa...d8aae5 )
by Ivannis Suárez
19:41
created

Bus::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Cubiche\Core\Bus;
12
13
use Cubiche\Core\Bus\Exception\InvalidMiddlewareException;
14
use Cubiche\Core\Bus\Middlewares\MiddlewareInterface;
15
use Cubiche\Core\Collections\ArrayCollection\ArrayList;
16
use Cubiche\Core\Collections\ArrayCollection\SortedArrayHashMap;
17
use Cubiche\Core\Comparable\Comparator;
18
use Cubiche\Core\Comparable\ReverseComparator;
19
use Cubiche\Core\Delegate\Delegate;
20
use Cubiche\Core\Specification\Criteria;
21
22
/**
23
 * Bus class.
24
 *
25
 * @author Ivannis Suárez Jerez <[email protected]>
26
 */
27
class Bus implements BusInterface
28
{
29
    /**
30
     * @var SortedArrayHashMap
31
     */
32
    protected $middlewares;
33
34
    /**
35
     * Bus constructor.
36
     *
37
     * @param MiddlewareInterface[] $middlewares
38
     */
39
    public function __construct(array $middlewares = array())
40
    {
41
        $this->middlewares = new SortedArrayHashMap([], new ReverseComparator(new Comparator()));
42
        foreach ($middlewares as $priority => $middleware) {
43
            if (!$middleware instanceof MiddlewareInterface) {
44
                throw InvalidMiddlewareException::forUnknownValue($middleware);
45
            }
46
47
            $this->addMiddleware($middleware, $priority);
48
        }
49
    }
50
51
    /**
52
     * Adds a middleware to the middleware list. The higher priority value, the earlier a middleware
53
     * will be triggered in the chain (defaults to 0).
54
     *
55
     * @param MiddlewareInterface $middleware
56
     * @param int                 $priority
57
     */
58
    public function addMiddleware(MiddlewareInterface $middleware, $priority = 0)
59
    {
60
        if (!$this->middlewares->containsKey($priority)) {
61
            $this->middlewares->set($priority, new ArrayList());
62
        }
63
64
        /** @var ArrayList $middlewares */
65
        $middlewares = $this->middlewares->get($priority);
66
        if ($middlewares->findOne(Criteria::eq($middleware)) === null) {
67
            $middlewares->add($middleware);
68
        }
69
    }
70
71
    /**
72
     * Add a middleware before a given middleware.
73
     *
74
     * @param MiddlewareInterface $middleware
75
     * @param MiddlewareInterface $target
76
     *
77
     * @throws \InvalidArgumentException
78
     */
79 View Code Duplication
    public function addMiddlewareBefore(MiddlewareInterface $middleware, MiddlewareInterface $target)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
    {
81
        $priority = $this->middlewarePriority($target);
82
        if ($priority === null) {
83
            throw new \InvalidArgumentException(
84
                sprintf(
85
                    'There is not a middleware of type %s registered.',
86
                    get_class($target)
87
                )
88
            );
89
        }
90
91
        $this->addMiddleware($middleware, $priority + 1);
92
    }
93
94
    /**
95
     * Add a middleware before a given middleware.
96
     *
97
     * @param MiddlewareInterface $middleware
98
     * @param MiddlewareInterface $target
99
     *
100
     * @throws \InvalidArgumentException
101
     */
102 View Code Duplication
    public function addMiddlewareAfter(MiddlewareInterface $middleware, MiddlewareInterface $target)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
    {
104
        $priority = $this->middlewarePriority($target);
105
        if ($priority === null) {
106
            throw new \InvalidArgumentException(
107
                sprintf(
108
                    'There is not a middleware of type %s registered.',
109
                    get_class($target)
110
                )
111
            );
112
        }
113
114
        $this->addMiddleware($middleware, $priority - 1);
115
    }
116
117
    /**
118
     * @param MiddlewareInterface $middleware
119
     *
120
     * @return int|null
121
     */
122
    protected function middlewarePriority(MiddlewareInterface $middleware)
123
    {
124
        /** @var ArrayList $collection */
125
        foreach ($this->middlewares as $priority => $collection) {
126
            $targetMiddleware = $collection->findOne(Criteria::eq($middleware));
127
            if ($targetMiddleware !== null) {
128
                return $priority;
129
            }
130
        }
131
132
        return;
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function dispatch(MessageInterface $message)
139
    {
140
        $chainedMiddleware = $this->chainedExecution();
141
142
        return $chainedMiddleware($message);
143
    }
144
145
    /**
146
     * @return Delegate
147
     */
148
    private function chainedExecution()
149
    {
150
        $middlewares = [];
151
        foreach ($this->middlewares as $priority => $collection) {
152
            foreach ($collection as $middleware) {
153
                $middlewares[] = $middleware;
154
            }
155
        }
156
157
        $next = Delegate::fromClosure(function ($message) {
158
            // the final middleware return the same message
159
            return $message;
160
        });
161
162
        // reverse iteration over middlewares
163
        /** @var MiddlewareInterface $middleware */
164
        while ($middleware = array_pop($middlewares)) {
165
            $next = Delegate::fromClosure(function ($message) use ($middleware, $next) {
166
                return $middleware->handle($message, $next);
167
            });
168
        }
169
170
        return $next;
171
    }
172
}
173