Passed
Branch master (748c89)
by Schlaefer
02:24
created

MiddlewareQueue::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @author  PhileCMS
4
 * @link    https://philecms.com
5
 * @license http://opensource.org/licenses/MIT
6
 */
7
8
namespace Phile\Http;
9
10
use IteratorAggregate;
11
use IteratorIterator;
12
use Psr\Http\Server\MiddlewareInterface;
13
use SplPriorityQueue;
14
use Traversable;
15
16
/**
17
 * Middleware queue
18
 */
19
class MiddlewareQueue implements IteratorAggregate
20
{
21
    public const DEFAULT_PRIORITY = 100;
22
    
23
    /** @var int counter for FIFO order for items with same priority */
24
    protected $serial = PHP_INT_MAX;
25
26
    /** @var SplPriorityQueue middleware */
27
    protected $queue;
28
29 5
    public function __construct()
30
    {
31 5
        $this->queue = new SplPriorityQueue();
32 5
    }
33
34
    /**
35
     * Adds middleware to queue
36
     *
37
     * @param MiddlewareInterface $middleware
38
     * @param int $priority
39
     * @return \self
40
     */
41 5
    public function add(MiddlewareInterface $middleware, int $priority = self::DEFAULT_PRIORITY): self
42
    {
43 5
        $this->queue->insert($middleware, [$priority, $this->serial--]);
44 5
        return $this;
45
    }
46
47
    /**
48
     * Implements IteratorAggregate
49
     *
50
     * @return Traversable
51
     */
52 5
    public function getIterator(): Traversable
53
    {
54 5
        return new IteratorIterator($this->queue);
55
    }
56
}
57