Passed
Pull Request — master (#521)
by
unknown
13:53 queued 12:16
created

OrientatedItemFactory::getBestOrientation()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 39
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3

Importance

Changes 14
Bugs 3 Features 0
Metric Value
cc 3
eloc 15
c 14
b 3
f 0
nc 4
nop 12
dl 0
loc 39
ccs 20
cts 20
cp 1
crap 3
rs 9.7666

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 Psr\Log\LoggerAwareInterface;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\NullLogger;
14
15
use function array_filter;
16
use function count;
17
use function usort;
18
19
/**
20
 * Figure out orientations for an item and a given set of dimensions.
21
 * @internal
22
 */
23
class OrientatedItemFactory implements LoggerAwareInterface
24
{
25
    protected LoggerInterface $logger;
26
27
    protected bool $singlePassMode = false;
28
29
    protected bool $boxIsRotated = false;
30
31
    /**
32
     * @var array<string, bool>
33
     */
34
    protected static array $emptyBoxStableItemOrientationCache = [];
35
36 84
    public function __construct(protected Box $box)
37
    {
38 84
        $this->logger = new NullLogger();
39
    }
40
41 84
    public function setLogger(LoggerInterface $logger): void
42
    {
43 84
        $this->logger = $logger;
44
    }
45
46 4
    public function setSinglePassMode(bool $singlePassMode): void
47
    {
48 4
        $this->singlePassMode = $singlePassMode;
49
    }
50
51 84
    public function setBoxIsRotated(bool $boxIsRotated): void
52
    {
53 84
        $this->boxIsRotated = $boxIsRotated;
54
    }
55
56
    /**
57
     * Get the best orientation for an item.
58
     */
59 84
    public function getBestOrientation(
60
        Item $item,
61
        ?OrientatedItem $prevItem,
62
        ItemList $nextItems,
63
        int $widthLeft,
64
        int $lengthLeft,
65
        int $depthLeft,
66
        int $rowLength,
67
        int $x,
68
        int $y,
69
        int $z,
70
        PackedItemList $prevPackedItemList,
0 ignored issues
show
Bug introduced by
The type DVDoug\BoxPacker\PackedItemList was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
        bool $considerStability
72
    ): ?OrientatedItem {
73 84
        $this->logger->debug(
74 84
            "evaluating item {$item->getDescription()} for fit",
75 84
            [
76 84
                'item' => $item,
77 84
                'space' => [
78 84
                    'widthLeft' => $widthLeft,
79 84
                    'lengthLeft' => $lengthLeft,
80 84
                    'depthLeft' => $depthLeft,
81 84
                ],
82 84
            ]
83 84
        );
84
85 84
        $possibleOrientations = $this->getPossibleOrientations($item, $prevItem, $widthLeft, $lengthLeft, $depthLeft, $x, $y, $z, $prevPackedItemList);
86 84
        $usableOrientations = $considerStability ? $this->getUsableOrientations($item, $possibleOrientations) : $possibleOrientations;
87
88 84
        if (empty($usableOrientations)) {
89 80
            return null;
90
        }
91
92 82
        $sorter = new OrientatedItemSorter($this, $this->singlePassMode, $widthLeft, $lengthLeft, $depthLeft, $nextItems, $rowLength, $x, $y, $z, $prevPackedItemList, $this->logger);
93 82
        usort($usableOrientations, $sorter);
94
95 82
        $this->logger->debug('Selected best fit orientation', ['orientation' => $usableOrientations[0]]);
96
97 82
        return $usableOrientations[0];
98
    }
99
100
    /**
101
     * Find all possible orientations for an item.
102
     *
103
     * @return OrientatedItem[]
104
     */
105 84
    public function getPossibleOrientations(
106
        Item $item,
107
        ?OrientatedItem $prevItem,
108
        int $widthLeft,
109
        int $lengthLeft,
110
        int $depthLeft,
111
        int $x,
112
        int $y,
113
        int $z,
114
        PackedItemList $prevPackedItemList
115
    ): array {
116 84
        $permutations = $this->generatePermutations($item, $prevItem);
117
118
        // remove any that simply don't fit
119 84
        $orientations = [];
120 84
        foreach ($permutations as $dimensions) {
121 84
            if ($dimensions[0] <= $widthLeft && $dimensions[1] <= $lengthLeft && $dimensions[2] <= $depthLeft) {
122 82
                $orientations[] = new OrientatedItem($item, $dimensions[0], $dimensions[1], $dimensions[2]);
123
            }
124
        }
125
126 84
        if ($item instanceof ConstrainedPlacementItem && !$this->box instanceof WorkingVolume) {
127
            $orientations = array_filter($orientations, function (OrientatedItem $i) use ($x, $y, $z, $prevPackedItemList): bool {
128
                /** @var ConstrainedPlacementItem $constrainedItem */
129
                $constrainedItem = $i->getItem();
130
131
                if ($this->boxIsRotated) {
132
                    $rotatedPrevPackedItemList = new PackedItemList();
133
                    foreach ($prevPackedItemList as $prevPackedItem) {
134
                        $rotatedPrevPackedItemList->insert(new PackedItem($prevPackedItem->getItem(), $prevPackedItem->getY(), $prevPackedItem->getX(), $prevPackedItem->getZ(), $prevPackedItem->getLength(), $prevPackedItem->getWidth(), $prevPackedItem->getDepth()));
135
                    }
136
137
                    return $constrainedItem->canBePacked(new PackedBox($this->box, $rotatedPrevPackedItemList), $y, $x, $z, $i->getLength(), $i->getWidth(), $i->getDepth());
138
                } else {
139
                    return $constrainedItem->canBePacked(new PackedBox($this->box, $prevPackedItemList), $x, $y, $z, $i->getWidth(), $i->getLength(), $i->getDepth());
140
                }
141
            });
142
        }
143
144 84
        return $orientations;
145
    }
146
147
    /**
148
     * @param  OrientatedItem[] $possibleOrientations
149
     * @return OrientatedItem[]
150
     */
151 84
    protected function getUsableOrientations(
152
        Item $item,
153
        array $possibleOrientations
154
    ): array {
155 84
        $stableOrientations = $unstableOrientations = [];
156
157
        // Divide possible orientations into stable (low centre of gravity) and unstable (high centre of gravity)
158 84
        foreach ($possibleOrientations as $orientation) {
159 82
            if ($orientation->isStable() || $this->box->getInnerDepth() === $orientation->getDepth()) {
160 82
                $stableOrientations[] = $orientation;
161
            } else {
162
                $unstableOrientations[] = $orientation;
163
            }
164
        }
165
166
        /*
167
         * We prefer to use stable orientations only, but allow unstable ones if
168
         * the item doesn't fit in the box any other way
169
         */
170 84
        if (count($stableOrientations) > 0) {
171 82
            return $stableOrientations;
172
        }
173
174 80
        if ((count($unstableOrientations) > 0) && !$this->hasStableOrientationsInEmptyBox($item)) {
175
            return $unstableOrientations;
176
        }
177
178 80
        return [];
179
    }
180
181
    /**
182
     * Return the orientations for this item if it were to be placed into the box with nothing else.
183
     */
184
    protected function hasStableOrientationsInEmptyBox(Item $item): bool
185
    {
186
        $cacheKey = $item->getWidth() .
187
            '|' .
188
            $item->getLength() .
189
            '|' .
190
            $item->getDepth() .
191
            '|' .
192
            $item->getAllowedRotation()->name .
0 ignored issues
show
Bug introduced by
The property name does not seem to exist on DVDoug\BoxPacker\Rotation.
Loading history...
193
            '|' .
194
            $this->box->getInnerWidth() .
195
            '|' .
196
            $this->box->getInnerLength() .
197
            '|' .
198
            $this->box->getInnerDepth();
199
200
        if (isset(static::$emptyBoxStableItemOrientationCache[$cacheKey])) {
201
            return static::$emptyBoxStableItemOrientationCache[$cacheKey];
202
        }
203
204
        $orientations = $this->getPossibleOrientations(
205
            $item,
206
            null,
207
            $this->box->getInnerWidth(),
208
            $this->box->getInnerLength(),
209
            $this->box->getInnerDepth(),
210
            0,
211
            0,
212
            0,
213
            new PackedItemList()
214
        );
215
216
        $stableOrientations = array_filter(
217
            $orientations,
218
            static fn (OrientatedItem $orientation) => $orientation->isStable()
219
        );
220
        static::$emptyBoxStableItemOrientationCache[$cacheKey] = count($stableOrientations) > 0;
221
222
        return static::$emptyBoxStableItemOrientationCache[$cacheKey];
223
    }
224
225
    /**
226
     * @return array<array<int>>
227
     */
228 84
    private function generatePermutations(Item $item, ?OrientatedItem $prevItem): array
229
    {
230
        // Special case items that are the same as what we just packed - keep orientation
231 84
        if ($prevItem && $prevItem->isSameDimensions($item)) {
232 62
            return [[$prevItem->getWidth(), $prevItem->getLength(), $prevItem->getDepth()]];
233
        }
234
235 84
        $permutations = [];
236 84
        $w = $item->getWidth();
237 84
        $l = $item->getLength();
238 84
        $d = $item->getDepth();
239
240 84
        $permutations[$w . '|' . $l . '|' . $d] = [$w, $l, $d];
241
242 84
        if ($item->getAllowedRotation() !== Rotation::Never) { // simple 2D rotation
243 84
            $permutations[$l . '|' . $w . '|' . $d] = [$l, $w, $d];
244
        }
245
246 84
        if ($item->getAllowedRotation() === Rotation::BestFit) { // add 3D rotation if we're allowed
247 52
            $permutations[$w . '|' . $d . '|' . $l] = [$w, $d, $l];
248 52
            $permutations[$l . '|' . $d . '|' . $w] = [$l, $d, $w];
249 52
            $permutations[$d . '|' . $w . '|' . $l] = [$d, $w, $l];
250 52
            $permutations[$d . '|' . $l . '|' . $w] = [$d, $l, $w];
251
        }
252
253 84
        return $permutations;
254
    }
255
}
256