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 13
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 13
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 22
ccs 13
cts 13
cp 1
crap 3
rs 9.8333
1
<?php
2
3
/**
4
 * Box packing (3D bin packing, knapsack problem).
5
 *
6
 * @author Doug Wright
7
 */
8
declare(strict_types=1);
9
10
namespace DVDoug\BoxPacker;
11
12
use function usort;
13
14
/**
15
 * Applies load stability to generated result.
16
 * @internal
17
 */
18
class LayerStabiliser
19
{
20
    /**
21
     * @param PackedLayer[] $packedLayers
22
     *
23
     * @return PackedLayer[]
24 97
     */
25
    public function stabilise(array $packedLayers): array
26
    {
27 97
        // first re-order according to footprint
28 97
        $stabilisedLayers = [];
29
        usort($packedLayers, $this->compare(...));
30
31 97
        // then for each item in the layer, re-calculate each item's z position
32 97
        $currentZ = 0;
33 97
        foreach ($packedLayers as $oldZLayer) {
34 97
            $oldZStart = $oldZLayer->getStartZ();
35 97
            $newZLayer = new PackedLayer();
36 97
            foreach ($oldZLayer->getItems() as $oldZItem) {
37 97
                $newZ = $oldZItem->z - $oldZStart + $currentZ;
38 97
                $newZItem = new PackedItem($oldZItem->item, $oldZItem->x, $oldZItem->y, $newZ, $oldZItem->width, $oldZItem->length, $oldZItem->depth);
39
                $newZLayer->insert($newZItem);
40
            }
41 97
42 97
            $stabilisedLayers[] = $newZLayer;
43
            $currentZ += $newZLayer->getDepth();
44
        }
45 97
46
        return $stabilisedLayers;
47
    }
48 50
49
    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...
50 50
    {
51
        return ($layerB->getFootprint() <=> $layerA->getFootprint()) ?: ($layerB->getDepth() <=> $layerA->getDepth());
52
    }
53
}
54