Passed
Push — 1.x-dev ( afef98...3b2513 )
by Doug
02:45 queued 44s
created

ItemList::asArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem).
4
 *
5
 * @author Doug Wright
6
 */
7
8
namespace DVDoug\BoxPacker;
9
10
/**
11
 * List of items to be packed, ordered by volume.
12
 *
13
 * @author Doug Wright
14
 */
15
class ItemList extends \SplMaxHeap
16
{
17
    /**
18
     * Compare elements in order to place them correctly in the heap while sifting up.
19
     *
20
     * @see \SplMaxHeap::compare()
21
     *
22
     * @param mixed $itemA
23
     * @param mixed $itemB
24
     *
25
     * @return int
26
     */
27 22
    public function compare($itemA, $itemB)
28
    {
29 22
        if ($itemA->getVolume() > $itemB->getVolume()) {
30 11
            return 1;
31 22
        } elseif ($itemA->getVolume() < $itemB->getVolume()) {
32 10
            return -1;
33 20
        } elseif ($itemA->getWeight() !== $itemB->getWeight()) {
34 3
            return $itemA->getWeight() - $itemB->getWeight();
35 20
        } elseif ($itemA->getDescription() < $itemB->getDescription()) {
36 4
            return 1;
37
        } else {
38 18
            return -1;
39
        }
40
    }
41
42
    /**
43
     * Get copy of this list as a standard PHP array.
44
     *
45
     * @return Item[]
46
     */
47 5
    public function asArray()
48
    {
49 5
        $return = [];
50 5
        foreach (clone $this as $item) {
51 5
            $return[] = $item;
52
        }
53
54 5
        return $return;
55
    }
56
57
    /**
58
     * @internal
59
     *
60
     * @param  int      $n
61
     * @return ItemList
62
     */
63 12
    public function topN($n)
64
    {
65 12
        $workingList = clone $this;
66 12
        $topNList = new self();
67 12
        $i = 0;
68 12
        while(!$workingList->isEmpty() && $i < $n) {
69 12
            $topNList->insert($workingList->extract());
70
        }
71
72 12
        return $topNList;
73
    }
74
75
}
76