Passed
Push — 3.x ( 071761...f78397 )
by Doug
03:06
created

BoxList   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 58
ccs 15
cts 15
cp 1
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 2
A fromArray() 0 7 1
A getIterator() 0 8 2
A insert() 0 3 1
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
     * @var BoxSorter
39
     */
40
    private $sorter;
41
42 48
    public function __construct(?BoxSorter $sorter = null)
43
    {
44 48
        $this->sorter = $sorter ?: new DefaultBoxSorter();
45 48
    }
46
47
    /**
48
     * Do a bulk create.
49
     *
50
     * @param Box[] $boxes
51
     *
52
     * @return BoxList
53
     */
54 2
    public static function fromArray(array $boxes, bool $preSorted = false): self
55
    {
56 2
        $list = new static();
57 2
        $list->list = $boxes;
58 2
        $list->isSorted = $preSorted;
59
60 2
        return $list;
61
    }
62
63
    /**
64
     * @return Traversable|Box[]
65
     */
66 47
    public function getIterator(): Traversable
67
    {
68 47
        if (!$this->isSorted) {
69 46
            usort($this->list, [$this->sorter, 'compare']);
70 46
            $this->isSorted = true;
71
        }
72
73 47
        return new ArrayIterator($this->list);
74
    }
75
76 44
    public function insert(Box $item): void
77
    {
78 44
        $this->list[] = $item;
79 44
    }
80
}
81