Passed
Push — master ( 79d4e4...fedc6a )
by Doug
03:25
created

LayerStabiliser::stabilise()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 13
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 22
ccs 14
cts 14
cp 1
crap 3
rs 9.8333
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 function usort;
12
13
/**
14
 * Applies load stability to generated result.
15
 * @internal
16
 */
17
class LayerStabiliser
18
{
19
    /**
20
     * @param PackedLayer[] $packedLayers
21
     *
22
     * @return PackedLayer[]
23
     */
24 87
    public function stabilise(array $packedLayers): array
25
    {
26
        // first re-order according to footprint
27 87
        $stabilisedLayers = [];
28 87
        usort($packedLayers, $this->compare(...));
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ')' on line 28 at column 47
Loading history...
29
30
        // then for each item in the layer, re-calculate each item's z position
31 87
        $currentZ = 0;
32 87
        foreach ($packedLayers as $oldZLayer) {
33 87
            $oldZStart = $oldZLayer->getStartZ();
34 87
            $newZLayer = new PackedLayer();
35 87
            foreach ($oldZLayer->getItems() as $oldZItem) {
36 87
                $newZ = $oldZItem->getZ() - $oldZStart + $currentZ;
37 87
                $newZItem = new PackedItem($oldZItem->getItem(), $oldZItem->getX(), $oldZItem->getY(), $newZ, $oldZItem->getWidth(), $oldZItem->getLength(), $oldZItem->getDepth());
38 87
                $newZLayer->insert($newZItem);
39
            }
40
41 87
            $stabilisedLayers[] = $newZLayer;
42 87
            $currentZ += $newZLayer->getDepth();
43
        }
44
45 87
        return $stabilisedLayers;
46
    }
47
48 44
    private function compare(PackedLayer $layerA, PackedLayer $layerB): int
49
    {
50 44
        return ($layerB->getFootprint() <=> $layerA->getFootprint()) ?: ($layerB->getDepth() <=> $layerA->getDepth());
51
    }
52
}
53