RoundRobin::compare()   A
last analyzed

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 2
1
<?php
2
namespace PhillipsData\PrioritySchedule;
3
4
use SplHeap;
5
use RuntimeException;
6
use PhillipsData\PrioritySchedule\Exceptions\NoSuchElementException;
7
8
/**
9
 * Round Robin Priority Scehdule implemented using a Heap
10
 */
11
class RoundRobin extends SplHeap implements ScheduleInterface
12
{
13
    /**
14
     * @var callable The comparator to use to determine the order
15
     */
16
    protected $callback;
17
18
    /**
19
     * Initialize the priority schedule
20
     */
21
    public function __construct()
22
    {
23
        $this->callback = function ($a, $b) {
24
            if ($a === $b) {
25
                return 0;
26
            }
27
            return $a < $b
28
                ? 1
29
                : -1;
30
        };
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     *
36
     * $callback Should accept a two parameters and return an int
37
     * (0 if items are equal, 1 to put left on top, -1 to put right on top)
38
     */
39
    public function setCallback(callable $callback)
40
    {
41
        $this->callback = $callback;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function compare($value1, $value2)
48
    {
49
        return call_user_func($this->callback, $value1, $value2);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function extract()
56
    {
57
        try {
58
            return parent::extract();
59
        } catch (RuntimeException $e) {
60
            throw new NoSuchElementException(
61
                'Can not extract from empty heap.'
62
            );
63
        }
64
    }
65
}
66