LayerStabiliser::stabilise()   A
last analyzed

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 0
Metric Value
cc 3
eloc 13
nc 3
nop 1
dl 0
loc 22
ccs 14
cts 14
cp 1
crap 3
rs 9.8333
c 0
b 0
f 0
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 95
    public function stabilise(array $packedLayers): array
25
    {
26
        // first re-order according to footprint
27 95
        $stabilisedLayers = [];
28 95
        usort($packedLayers, $this->compare(...));
29
30
        // then for each item in the layer, re-calculate each item's z position
31 95
        $currentZ = 0;
32 95
        foreach ($packedLayers as $oldZLayer) {
33 95
            $oldZStart = $oldZLayer->getStartZ();
34 95
            $newZLayer = new PackedLayer();
35 95
            foreach ($oldZLayer->getItems() as $oldZItem) {
36 95
                $newZ = $oldZItem->z - $oldZStart + $currentZ;
37 95
                $newZItem = new PackedItem($oldZItem->item, $oldZItem->x, $oldZItem->y, $newZ, $oldZItem->width, $oldZItem->length, $oldZItem->depth);
38 95
                $newZLayer->insert($newZItem);
39
            }
40
41 95
            $stabilisedLayers[] = $newZLayer;
42 95
            $currentZ += $newZLayer->getDepth();
43
        }
44
45 95
        return $stabilisedLayers;
46
    }
47
48 48
    private function compare(PackedLayer $layerA, PackedLayer $layerB): int
0 ignored issues
show
Unused Code introduced by
The method compare() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
49
    {
50 48
        return ($layerB->getFootprint() <=> $layerA->getFootprint()) ?: ($layerB->getDepth() <=> $layerA->getDepth());
51
    }
52
}
53