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