Passed
Pull Request — master (#294)
by
unknown
18:38 queued 14:21
created

BoxList::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 7
ccs 0
cts 5
cp 0
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
class BoxList implements IteratorAggregate
20
{
21
    /** @var Box[] */
22
    private array $list = [];
23
24
    private bool $isSorted = false;
25
26
    private BoxSorter $sorter;
27
28 24
    public function __construct(?BoxSorter $sorter = null)
29
    {
30 24
        $this->sorter = $sorter ?: new DefaultBoxSorter();
31
    }
32
33
    /**
34
     * Do a bulk create.
35
     *
36
     * @param  Box[]   $boxes
37
     * @return BoxList
38
     */
39
    public static function fromArray(array $boxes, bool $preSorted = false): self
40
    {
41
        $list = new self();
42
        $list->list = $boxes;
43
        $list->isSorted = $preSorted;
44
45
        return $list;
46
    }
47
48
    /**
49
     * @return Traversable<Box>
50
     */
51 24
    public function getIterator(): Traversable
52
    {
53 24
        if (!$this->isSorted) {
54 24
            usort($this->list, [$this->sorter, 'compare']);
55 24
            $this->isSorted = true;
56
        }
57
58 24
        return new ArrayIterator($this->list);
59
    }
60
61 24
    public function insert(Box $item): void
62
    {
63 24
        $this->list[] = $item;
64
    }
65
}
66