Completed
Push — master ( 17ecec...f96e7f )
by Doug
51:32 queued 50:04
created

src/BoxList.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem)
4
 * @package BoxPacker
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
namespace DVDoug\BoxPacker;
9
10
use ArrayIterator, IteratorAggregate, Traversable;
11
12
/**
13
 * List of boxes available to put items into, ordered by volume
14
 * @author Doug Wright
15
 * @package BoxPacker
16
 */
17
class BoxList implements IteratorAggregate
18
{
19
    /**
20
     * List containing boxes
21
     * @var Box[]
22
     */
23
    private $list = [];
24
25
    /**
26
     * Has this list already been sorted?
27
     * @var bool
28
     */
29
    private $isSorted = false;
30
31
    /**
32
     * @return Traversable
33
     */
34 29 View Code Duplication
    public function getIterator(): Traversable
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
    {
36 29
        if (!$this->isSorted) {
37 29
            usort($this->list, [$this, 'compare']);
38 29
            $this->isSorted = true;
39
        }
40 29
        return new ArrayIterator($this->list);
41
    }
42
43
    /**
44
     * @param Box $item
45
     */
46 28
    public function insert(Box $item)
47
    {
48 28
        $this->list[] = $item;
49
    }
50
51
    /**
52
     * @param Box $boxA
53
     * @param Box $boxB
54
     *
55
     * @return int
56
     */
57 10
    public function compare($boxA, $boxB): int
58
    {
59 10
        $boxAVolume = $boxA->getInnerWidth() * $boxA->getInnerLength() * $boxA->getInnerDepth();
60 10
        $boxBVolume = $boxB->getInnerWidth() * $boxB->getInnerLength() * $boxB->getInnerDepth();
61
62 10
        return $boxAVolume <=> $boxBVolume;
63
    }
64
}
65