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

BoxList   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 64.29%

Importance

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

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
    /**
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