FirstAvailable::extract()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
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
        $this->setIteratorMode(
26
            SplQueue::IT_MODE_DELETE
27
        );
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     *
33
     * $callback Should accept a single parameter and return a bool
34
     * (true if valid, false otherwise)
35
     */
36
    public function setCallback(callable $callback)
37
    {
38
        $this->callbackFilter = $callback;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function insert($item)
45
    {
46
        if (call_user_func($this->callbackFilter, $item)) {
47
            $this->enqueue($item);
48
            $this->rewind();
49
        }
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function extract()
56
    {
57
        if (!$this->valid()) {
58
            throw new NoSuchElementException(
59
                'Can not extract from empty queue.'
60
            );
61
        }
62
        return $this->current();
63
    }
64
}
65