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

PriorityQueueDispatcher   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 48
rs 10
c 1
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addStack() 0 18 4
A add() 0 11 2
A sortMiddleware() 0 4 1
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