Test Failed
Push — 2.x-dev ( 5e90af...eccc16 )
by Doug
03:16
created

LayerStabiliser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 40
ccs 16
cts 16
cp 1
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A compare() 0 3 2
A stabilise() 0 22 3
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem).
4
 *
5
 * @author Doug Wright
6
 */
7
namespace DVDoug\BoxPacker;
8
9
/**
10
 * Applies load stability to generated result.
11
 *
12
 * @author Doug Wright
13
 * @internal
14
 */
15
class LayerStabiliser
16
{
17
    /**
18
     * @param PackedLayer[] $packedLayers
19
     *
20
     * @return PackedLayer[]
21
     */
22 13
    public function stabilise(array $packedLayers)
23
    {
24
        // first re-order according to footprint
25 13
        $stabilisedLayers = [];
26 13
        usort($packedLayers, [$this, 'compare']);
27
28
        // then for each item in the layer, re-calculate each item's z position
29 13
        $currentZ = 0;
30 13
        foreach ($packedLayers as $oldZLayer) {
31 13
            $oldZStart = $oldZLayer->getStartDepth();
32 13
            $newZLayer = new PackedLayer();
33 13
            foreach ($oldZLayer->getItems() as $oldZItem) {
34 13
                $newZ = $oldZItem->getZ() - $oldZStart + $currentZ;
35 13
                $newZItem = new PackedItem($oldZItem->getItem(), $oldZItem->getX(), $oldZItem->getY(), $newZ, $oldZItem->getWidth(), $oldZItem->getLength(), $oldZItem->getDepth());
36 13
                $newZLayer->insert($newZItem);
37
            }
38
39 13
            $stabilisedLayers[] = $newZLayer;
40 13
            $currentZ += $newZLayer->getDepth();
41
        }
42
43 13
        return $stabilisedLayers;
44
    }
45
46
    /**
47
     * @param PackedLayer $layerA
48
     * @param PackedLayer $layerB
49
     *
50
     * @return int
51
     */
52 5
    private function compare(PackedLayer $layerA, PackedLayer $layerB)
53
    {
54 5
        return ($layerB->getFootprint() - $layerA->getFootprint()) ?: ($layerB->getDepth() - $layerA->getDepth());
55
    }
56
}
57