Passed
Pull Request — master (#308)
by
unknown
05:50 queued 03:55
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
15
use function usort;
16
17
/**
18
 * List of boxes available to put items into, ordered by volume.
19
 */
20
class BoxList implements IteratorAggregate
21
{
22
    /** @var Box[] */
23
    private array $list = [];
24
25
    private bool $isSorted = false;
26
27
    private BoxSorter $sorter;
28
29 24
    public function __construct(?BoxSorter $sorter = null)
30
    {
31 24
        $this->sorter = $sorter ?: new DefaultBoxSorter();
32
    }
33
34
    /**
35
     * Do a bulk create.
36
     *
37
     * @param  Box[]   $boxes
38
     * @return BoxList
39
     */
40
    public static function fromArray(array $boxes, bool $preSorted = false): self
41
    {
42
        $list = new self();
43
        $list->list = $boxes;
44
        $list->isSorted = $preSorted;
45
46
        return $list;
47
    }
48
49
    /**
50
     * @return Traversable<Box>
51
     */
52 24
    public function getIterator(): Traversable
53
    {
54 24
        if (!$this->isSorted) {
55 24
            usort($this->list, [$this->sorter, 'compare']);
56 24
            $this->isSorted = true;
57
        }
58
59 24
        return new ArrayIterator($this->list);
60
    }
61
62 24
    public function insert(Box $item): void
63
    {
64 24
        $this->list[] = $item;
65
    }
66
}
67