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

BoxList::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
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