PriorityQueueDispatcher   A
last analyzed

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
 * @created      10.03.2019
8
 * @author       smiley <[email protected]>
9
 * @copyright    2019 smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\HTTP\Psr15;
14
15
use Psr\Http\Server\MiddlewareInterface;
16
17
use function usort;
18
19
class PriorityQueueDispatcher extends QueueDispatcher{
20
21
	/**
22
	 * @inheritDoc
23
	 */
24
	public function addStack(iterable $middlewareStack):QueueDispatcher{
25
26
		foreach($middlewareStack as $middleware){
27
28
			if(!$middleware instanceof MiddlewareInterface){
29
				throw new MiddlewareException('invalid middleware');
30
			}
31
32
			if(!$middleware instanceof PriorityMiddlewareInterface){
33
				$middleware = new PriorityMiddleware($middleware);
34
			}
35
36
			$this->middlewareStack[] = $middleware;
37
		}
38
39
		$this->sortMiddleware();
40
41
		return $this;
42
	}
43
44
	/**
45
	 * @inheritDoc
46
	 */
47
	public function add(MiddlewareInterface $middleware):QueueDispatcher{
48
49
		if(!$middleware instanceof PriorityMiddlewareInterface){
50
			$middleware = new PriorityMiddleware($middleware);
51
		}
52
53
		$this->middlewareStack[] = $middleware;
54
55
		$this->sortMiddleware();
56
57
		return $this;
58
	}
59
60
	/**
61
	 *
62
	 */
63
	protected function sortMiddleware():void{
64
		usort(
65
			$this->middlewareStack,
66
			fn(PriorityMiddlewareInterface $a, PriorityMiddlewareInterface $b) => $b->getPriority() <=> $a->getPriority()
67
		);
68
	}
69
70
}
71