Completed
Push — master ( 723741...e2f01d )
by smiley
02:37
created

PriorityQueueRequestHandler::sortMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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