Passed
Pull Request — master (#314)
by
unknown
05:46 queued 03:57
created

BoxList   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 64.29%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 13
c 2
b 1
f 0
dl 0
loc 45
ccs 9
cts 14
cp 0.6429
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 2
A getIterator() 0 8 2
A insert() 0 3 1
A fromArray() 0 7 1
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