Passed
Push — 1.x-dev ( 8f914b...081a6e )
by Doug
04:31
created

BoxList::compare()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7.0957

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 7
nop 2
dl 0
loc 30
ccs 14
cts 16
cp 0.875
crap 7.0957
rs 8.8333
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 boxes available to put items into, ordered by volume.
12
 *
13
 * @author Doug Wright
14
 */
15
class BoxList extends \SplMinHeap
16
{
17
    /**
18
     * Compare elements in order to place them correctly in the heap while sifting up.
19
     *
20
     * @see \SplMinHeap::compare()
21
     *
22
     * @param Box $boxA
23
     * @param Box $boxB
24
     *
25
     * @return int
26
     */
27 9
    public function compare($boxA, $boxB)
28
    {
29 9
        $boxAVolume = $boxA->getInnerWidth() * $boxA->getInnerLength() * $boxA->getInnerDepth();
30 9
        $boxBVolume = $boxB->getInnerWidth() * $boxB->getInnerLength() * $boxB->getInnerDepth();
31
32
        // try smallest box first
33 9
        if ($boxBVolume > $boxAVolume) {
34 8
            return 1;
35
        }
36 4
        if ($boxAVolume > $boxBVolume) {
37 1
            return -1;
38
        }
39
40
        // smallest empty weight
41 4
        if ($boxB->getEmptyWeight() > $boxA->getEmptyWeight()) {
42
            return 1;
43
        }
44 4
        if ($boxA->getEmptyWeight() > $boxB->getEmptyWeight()) {
45
            return -1;
46
        }
47
48
        // maximum weight capacity as fallback decider
49 4
        if ($boxB->getMaxWeight() > $boxA->getMaxWeight()) {
50 1
            return 1;
51
        }
52 4
        if ($boxA->getMaxWeight() > $boxB->getMaxWeight()) {
53 1
            return -1;
54
        }
55
56 3
        return 0;
57
    }
58
}
59