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

BoxList::sort()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 13
cts 14
cp 0.9286
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 2
nop 0
crap 4.0058
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