Passed
Push — dependabot/npm_and_yarn/docs/v... ( cbefaf )
by
unknown
08:40
created

BoxList::insert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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