Passed
Push — master ( a359e3...00dca5 )
by Doug
03:21 queued 12s
created

BoxList::insert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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
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
     * Do a bulk create.
39
     *
40
     * @param  Box[]   $items
41
     * @return BoxList
42
     */
43 2
    public static function fromArray(array $boxes, bool $preSorted = false): self
44
    {
45 2
        $list = new static();
46 2
        $list->list = $boxes;
47 2
        $list->isSorted = $preSorted;
48
49 2
        return $list;
50
    }
51
52
    /**
53
     * @return Traversable<Box>
54
     */
55 39
    public function getIterator(): Traversable
56
    {
57 39
        if (!$this->isSorted) {
58 38
            usort($this->list, [$this, 'compare']);
59 38
            $this->isSorted = true;
60
        }
61
62 39
        return new ArrayIterator($this->list);
63
    }
64
65 36
    public function insert(Box $item): void
66
    {
67 36
        $this->list[] = $item;
68 36
    }
69
70
    /**
71
     * @param Box $boxA
72
     * @param Box $boxB
73
     */
74 23
    public static function compare($boxA, $boxB): int
75
    {
76 23
        $boxAVolume = $boxA->getInnerWidth() * $boxA->getInnerLength() * $boxA->getInnerDepth();
77 23
        $boxBVolume = $boxB->getInnerWidth() * $boxB->getInnerLength() * $boxB->getInnerDepth();
78
79 23
        $volumeDecider = $boxAVolume <=> $boxBVolume; // try smallest box first
80
81 23
        if ($volumeDecider !== 0) {
82 19
            return $volumeDecider;
83
        }
84
85 4
        $emptyWeightDecider = $boxA->getEmptyWeight() <=> $boxB->getEmptyWeight(); // with smallest empty weight
86 4
        if ($emptyWeightDecider !== 0) {
87 4
            return $emptyWeightDecider;
88
        }
89
90
        // maximum weight capacity as fallback decider
91 1
        return ($boxA->getMaxWeight() - $boxA->getEmptyWeight()) <=> ($boxB->getMaxWeight() - $boxB->getEmptyWeight());
92
    }
93
}
94