Passed
Push — master ( b3e52b...de1ca6 )
by Doug
11:09
created

BoxList::compare()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 3
rs 9.9666
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem).
4
 *
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
9
namespace DVDoug\BoxPacker;
10
11
use ArrayIterator;
12
use IteratorAggregate;
13
use Traversable;
14
use function usort;
15
16
/**
17
 * List of boxes available to put items into, ordered by volume.
18
 *
19
 * @author Doug Wright
20
 */
21
class BoxList implements IteratorAggregate
22
{
23
    /**
24
     * List containing boxes.
25
     *
26
     * @var Box[]
27
     */
28
    private $list = [];
29
30
    /**
31
     * Has this list already been sorted?
32
     *
33
     * @var bool
34
     */
35
    private $isSorted = false;
36
37
    /**
38
     * @return Traversable
39
     */
40 26
    public function getIterator(): Traversable
41
    {
42 26
        if (!$this->isSorted) {
43 26
            usort($this->list, [$this, 'compare']);
44 26
            $this->isSorted = true;
45
        }
46
47 26
        return new ArrayIterator($this->list);
48
    }
49
50
    /**
51
     * @param Box $item
52
     */
53 25
    public function insert(Box $item): void
54
    {
55 25
        $this->list[] = $item;
56 25
    }
57
58
    /**
59
     * @param Box $boxA
60
     * @param Box $boxB
61
     *
62
     * @return int
63
     */
64 13
    public function compare($boxA, $boxB): int
65
    {
66 13
        $boxAVolume = $boxA->getInnerWidth() * $boxA->getInnerLength() * $boxA->getInnerDepth();
67 13
        $boxBVolume = $boxB->getInnerWidth() * $boxB->getInnerLength() * $boxB->getInnerDepth();
68
69 13
        $volumeDecider = $boxAVolume <=> $boxBVolume; // try smallest box first
70 13
        $emptyWeightDecider = $boxB->getEmptyWeight() <=> $boxA->getEmptyWeight(); // with smallest empty weight
71
72 13
        if ($volumeDecider !== 0) {
73 12
            return $volumeDecider;
74
        }
75 1
        if ($emptyWeightDecider !== 0) {
76 1
            return $emptyWeightDecider;
77
        }
78
79
        // maximum weight capacity as fallback decider
80 1
        return ($boxA->getMaxWeight() - $boxA->getEmptyWeight()) <=> ($boxB->getMaxWeight() - $boxB->getEmptyWeight());
81
    }
82
}
83