Completed
Push — test_jit ( c34f6e...87859e )
by Doug
10:03
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 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
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
 *
16
 * @author Doug Wright
17
 * @internal
18
 */
19
class LayerStabiliser
20
{
21
    /**
22
     * @param PackedLayer[] $packedLayers
23
     *
24
     * @return PackedLayer[]
25
     */
26 56
    public function stabilise(array $packedLayers): array
27
    {
28
        // first re-order according to footprint
29 56
        $stabilisedLayers = [];
30 56
        usort($packedLayers, [$this, 'compare']);
31
32
        // then for each item in the layer, re-calculate each item's z position
33 56
        $currentZ = 0;
34 56
        foreach ($packedLayers as $oldZLayer) {
35 56
            $oldZStart = $oldZLayer->getStartDepth();
36 56
            $newZLayer = new PackedLayer();
37 56
            foreach ($oldZLayer->getItems() as $oldZItem) {
38 56
                $newZ = $oldZItem->getZ() - $oldZStart + $currentZ;
39 56
                $newZItem = new PackedItem($oldZItem->getItem(), $oldZItem->getX(), $oldZItem->getY(), $newZ, $oldZItem->getWidth(), $oldZItem->getLength(), $oldZItem->getDepth());
40 56
                $newZLayer->insert($newZItem);
41
            }
42
43 56
            $stabilisedLayers[] = $newZLayer;
44 56
            $currentZ += $newZLayer->getDepth();
45
        }
46
47 56
        return $stabilisedLayers;
48
    }
49
50 27
    private function compare(PackedLayer $layerA, PackedLayer $layerB): int
51
    {
52 27
        return ($layerB->getFootprint() <=> $layerA->getFootprint()) ?: ($layerB->getDepth() <=> $layerA->getDepth());
53
    }
54
}
55