Passed
Push — main ( f2efe3...53dc0a )
by smiley
10:15
created

PriorityQueueDispatcher::addStack()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 1
dl 0
loc 18
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Class PriorityQueueDispatcher
4
 *
5
 * @link https://github.com/libreworks/caridea-dispatch
6
 *
7
 * @filesource   PriorityQueueDispatcher.php
8
 * @created      10.03.2019
9
 * @package      chillerlan\HTTP\Psr15
10
 * @author       smiley <[email protected]>
11
 * @copyright    2019 smiley
12
 * @license      MIT
13
 */
14
15
namespace chillerlan\HTTP\Psr15;
16
17
use Psr\Http\Server\MiddlewareInterface;
18
19
use function usort;
20
21
class PriorityQueueDispatcher extends QueueDispatcher{
22
23
	/**
24
	 * @inheritDoc
25
	 */
26
	public function addStack(iterable $middlewareStack):QueueDispatcher{
27
28
		foreach($middlewareStack as $middleware){
29
30
			if(!$middleware instanceof MiddlewareInterface){
31
				throw new MiddlewareException('invalid middleware');
32
			}
33
34
			if(!$middleware instanceof PriorityMiddlewareInterface){
35
				$middleware = new PriorityMiddleware($middleware);
36
			}
37
38
			$this->middlewareStack[] = $middleware;
39
		}
40
41
		$this->sortMiddleware();
42
43
		return $this;
44
	}
45
46
	/**
47
	 * @inheritDoc
48
	 */
49
	public function add(MiddlewareInterface $middleware):QueueDispatcher{
50
51
		if(!$middleware instanceof PriorityMiddlewareInterface){
52
			$middleware = new PriorityMiddleware($middleware);
53
		}
54
55
		$this->middlewareStack[] = $middleware;
56
57
		$this->sortMiddleware();
58
59
		return $this;
60
	}
61
62
	/**
63
	 *
64
	 */
65
	protected function sortMiddleware():void{
66
		usort(
67
			$this->middlewareStack,
68
			fn(PriorityMiddlewareInterface $a, PriorityMiddlewareInterface $b) => $b->getPriority() <=> $a->getPriority()
69
		);
70
	}
71
72
}
73