BoxList::insert()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
/**
4
 * Box packing (3D bin packing, knapsack problem).
5
 *
6
 * @author Doug Wright
7
 */
8
declare(strict_types=1);
9
10
namespace DVDoug\BoxPacker;
11
12
use ArrayIterator;
13
use IteratorAggregate;
14
use Traversable;
15
16
use function usort;
17
18
/**
19
 * List of boxes available to put items into, ordered by volume.
20
 */
21
class BoxList implements IteratorAggregate
22
{
23
    /**
24
     * @var Box[]
25
     */
26
    private array $list = [];
27
28
    private bool $isSorted = false;
29 58
30
    public function __construct(private readonly BoxSorter $sorter = new DefaultBoxSorter())
31 58
    {
32
    }
33
34
    /**
35
     * Do a bulk create.
36
     *
37
     * @param Box[] $boxes
38 2
     */
39
    public static function fromArray(array $boxes, bool $preSorted = false): self
40 2
    {
41 2
        $list = new self();
42 2
        $list->list = $boxes;
43
        $list->isSorted = $preSorted;
44 2
45
        return $list;
46
    }
47
48
    /**
49
     * @return Traversable<Box>
50 57
     */
51
    public function getIterator(): Traversable
52 57
    {
53 56
        if (!$this->isSorted) {
54 56
            usort($this->list, $this->sorter->compare(...));
55
            $this->isSorted = true;
56
        }
57 57
58
        return new ArrayIterator($this->list);
59
    }
60 54
61
    public function insert(Box $item): void
62 54
    {
63
        $this->list[] = $item;
64
    }
65
}
66