Passed
Push — 1.x-dev ( cc1b76...09423a )
by Doug
02:10
created

LayerStabiliser::compare()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
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
8
namespace DVDoug\BoxPacker;
9
10
use Psr\Log\LoggerAwareInterface;
11
use Psr\Log\LoggerAwareTrait;
12
use Psr\Log\NullLogger;
13
14
/**
15
 * Applies load stability to generated result.
16
 *
17
 * @author Doug Wright
18
 */
19
class LayerStabiliser implements LoggerAwareInterface
20
{
21
    use LoggerAwareTrait;
22
23
    /**
24
     * Constructor.
25
     */
26 19
    public function __construct()
27
    {
28 19
        $this->logger = new NullLogger();
29 19
    }
30
31
    /**
32
     * @param PackedLayer[] $packedLayers
33
     *
34
     * @return PackedLayer[]
35
     */
36 19
    public function stabilise(array $packedLayers)
37
    {
38
        // first re-order according to footprint
39 19
        $stabilisedLayers = [];
40 19
        usort($packedLayers, [$this, 'compare']);
41
42
        // then for each item in the layer, re-calculate each item's z position
43 19
        $currentZ = 0;
44 19
        foreach ($packedLayers as $oldZLayer) {
45 19
            $oldZStart = $oldZLayer->getStartDepth();
46 19
            $newZLayer = new PackedLayer();
47 19
            foreach ($oldZLayer->getItems() as $oldZItem) {
48 19
                $newZ = $oldZItem->getZ() - $oldZStart + $currentZ;
49 19
                $newZItem = new PackedItem($oldZItem->getItem(), $oldZItem->getX(), $oldZItem->getY(), $newZ, $oldZItem->getWidth(), $oldZItem->getLength(), $oldZItem->getDepth());
50 19
                $newZLayer->insert($newZItem);
51
            }
52
53 19
            $stabilisedLayers[] = $newZLayer;
54 19
            $currentZ += $newZLayer->getDepth();
55
        }
56
57 19
        return $stabilisedLayers;
58
    }
59
60
    /**
61
     * @param PackedLayer $layerA
62
     * @param PackedLayer $layerB
63
     *
64
     * @return int
65
     */
66 11
    private function compare(PackedLayer $layerA, PackedLayer $layerB)
67
    {
68 11
        return ($layerB->getFootprint() - $layerA->getFootprint()) ?: ($layerB->getDepth() - $layerA->getDepth());
69
    }
70
}
71