Completed
Push — master ( c82fd5...c42739 )
by Cody
6s
created

FirstAvailable::key()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace PhillipsData\PrioritySchedule;
3
4
use SplQueue;
5
use PhillipsData\PrioritySchedule\Exceptions\NoSuchElementException;
6
7
/**
8
 * First Available Priorirty Schedule implemented using a Queue
9
 */
10
class FirstAvailable extends SplQueue implements ScheduleInterface
11
{
12
    /**
13
     * @var callable
14
     */
15
    protected $callbackFilter;
16
17
    /**
18
     * Initialize the priority schedule
19
     */
20
    public function __construct()
21
    {
22
        $this->callbackFilter = function ($item) {
23
            return (bool) $item;
24
        };
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     *
30
     * $callback Should accept a single parameter and return a bool
31
     * (true if valid, false otherwise)
32
     */
33
    public function setCallback(callable $callback)
34
    {
35
        $this->callbackFilter = $callback;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function insert($item)
42
    {
43
        if (call_user_func($this->callbackFilter, $item)) {
44
            $this->enqueue($item);
45
            $this->rewind();
46
        }
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function extract()
53
    {
54
        return $this->current();
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     *
60
     * @throws NoSuchElementException
61
     */
62
    public function current()
63
    {
64
        if (!$this->valid()) {
65
            throw new NoSuchElementException(
66
                'Can not extract from empty queue.'
67
            );
68
        }
69
        return parent::current();
70
    }
71
}
72