Completed
Push — new_data_structures_2 ( 960830 )
by Doug
05:29
created

BoxList::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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
     * @return int
25
     */
26
    public function count()
27
    {
28
        return count($this->list);
29
    }
30
31
    /**
32
     * @return \ArrayIterator
33
     */
34 21
    public function getIterator()
35
    {
36 21
        $this->sort();
37 21
        return new \ArrayIterator($this->list);
38
    }
39
40
    /**
41
     * Insert a box choice into the list
42
     *
43
     * @param Box $box
44
     */
45 20
    public function insert(Box $box)
46
    {
47 20
        $this->list[spl_object_hash($box)] = $box;
48 20
    }
49
50
    /**
51
     * Sort the boxes into order (smallest volume first)
52
     */
53 21
    protected function sort()
54
    {
55 21
        uasort(
56 21
            $this->list,
57 11
            function (Box $boxA, Box $boxB) {
58 11
                if ($boxB->getInnerVolume() > $boxA->getInnerVolume()) {
59 4
                    return -1;
60 10
                } elseif ($boxB->getInnerVolume() < $boxA->getInnerVolume()) {
61 10
                    return 1;
62
                } else {
63
                    return 0;
64
                }
65
            }
66 21
        );
67 21
    }
68
69
70
}
71