Completed
Push — master ( 9d7981...5c5914 )
by Doug
05:35
created

BoxList::insert()   A

Complexity

Conditions 1
Paths 1

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 5
Code Lines 3

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem)
4
 *
5
 * @package BoxPacker
6
 * @author Doug Wright
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
 * @package BoxPacker
15
 */
16
class BoxList implements \Countable, \IteratorAggregate
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $list = [];
22
23
    /**
24
     * @var bool
25
     */
26
    protected $isSorted = true;
27
28
    /**
29
     * @return int
30
     */
31
    public function count()
32
    {
33
        return count($this->list);
34
    }
35
36
    /**
37
     * @return \ArrayIterator
38
     */
39 21
    public function getIterator()
40
    {
41 21
        $this->sort();
42 21
        return new \ArrayIterator($this->list);
43
    }
44
45
    /**
46
     * Insert a box choice into the list
47
     *
48
     * @param Box $box
49
     */
50 20
    public function insert(Box $box)
51
    {
52 20
        $this->list[] = $box;
53 20
        $this->isSorted = false;
54 20
    }
55
56
    /**
57
     * Sort the boxes into order (smallest volume first)
58
     */
59 21
    protected function sort()
60
    {
61 21
        if (!$this->isSorted) {
62 20
            uasort(
63 20
                $this->list,
64 11
                function (Box $boxA, Box $boxB) {
65 11
                    if ($boxB->getInnerVolume() > $boxA->getInnerVolume()) {
66 4
                        return -1;
67 10
                    } elseif ($boxB->getInnerVolume() < $boxA->getInnerVolume()) {
68 10
                        return 1;
69
                    } else {
70
                        return 0;
71
                    }
72
                }
73 20
            );
74 20
            $this->isSorted = true;
75 20
        }
76 21
    }
77
}
78