Passed
Push — 3.x ( 33350c...688d36 )
by Doug
14:36
created

OrientatedItemFactory::getBestOrientation()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 40
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 14
Bugs 3 Features 0
Metric Value
cc 3
eloc 16
c 14
b 3
f 0
nc 4
nop 12
dl 0
loc 40
ccs 14
cts 14
cp 1
crap 3
rs 9.7333

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 function array_filter;
12
use function count;
13
use Psr\Log\LoggerAwareInterface;
14
use Psr\Log\LoggerAwareTrait;
15
use Psr\Log\NullLogger;
16
use function usort;
17
18
/**
19
 * Figure out orientations for an item and a given set of dimensions.
20
 *
21
 * @author Doug Wright
22
 * @internal
23
 */
24
class OrientatedItemFactory implements LoggerAwareInterface
25
{
26
    use LoggerAwareTrait;
27
28
    /** @var Box */
29
    protected $box;
30
31
    /**
32
     * Whether the packer is in single-pass mode.
33
     *
34
     * @var bool
35
     */
36
    protected $singlePassMode = false;
37
38
    /**
39
     * @var bool[]
40
     */
41
    protected static $emptyBoxStableItemOrientationCache = [];
42
43
    public function __construct(Box $box)
44
    {
45
        $this->box = $box;
46
        $this->logger = new NullLogger();
47
    }
48 72
49
    public function setSinglePassMode(bool $singlePassMode): void
50 72
    {
51 72
        $this->singlePassMode = $singlePassMode;
52 72
    }
53
54 62
    /**
55
     * Get the best orientation for an item.
56 62
     */
57 62
    public function getBestOrientation(
58
        Item $item,
59
        ?OrientatedItem $prevItem,
60
        ItemList $nextItems,
61
        int $widthLeft,
62 72
        int $lengthLeft,
63
        int $depthLeft,
64
        int $rowLength,
65
        int $x,
66
        int $y,
67
        int $z,
68
        PackedItemList $prevPackedItemList,
69
        bool $considerStability
70
    ): ?OrientatedItem {
71
        $this->logger->debug(
0 ignored issues
show
Bug introduced by
The method debug() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

71
        $this->logger->/** @scrutinizer ignore-call */ 
72
                       debug(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
72
            "evaluating item {$item->getDescription()} for fit",
73
            [
74
                'item' => $item,
75
                'space' => [
76 72
                    'widthLeft' => $widthLeft,
77 72
                    'lengthLeft' => $lengthLeft,
78
                    'depthLeft' => $depthLeft,
79 72
                ],
80
            ]
81 72
        );
82 72
83 72
        $possibleOrientations = $this->getPossibleOrientations($item, $prevItem, $widthLeft, $lengthLeft, $depthLeft, $x, $y, $z, $prevPackedItemList);
84
        $usableOrientations = $considerStability ? $this->getUsableOrientations($item, $possibleOrientations) : $possibleOrientations;
85
86
        if (empty($usableOrientations)) {
87
            return null;
88 72
        }
89 72
90
        $sorter = new OrientatedItemSorter($this, $this->singlePassMode, $widthLeft, $lengthLeft, $depthLeft, $nextItems, $rowLength, $x, $y, $z, $prevPackedItemList);
91 72
        $sorter->setLogger($this->logger);
0 ignored issues
show
Bug introduced by
It seems like $this->logger can also be of type null; however, parameter $logger of DVDoug\BoxPacker\OrientatedItemSorter::setLogger() does only seem to accept Psr\Log\LoggerInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

91
        $sorter->setLogger(/** @scrutinizer ignore-type */ $this->logger);
Loading history...
92 62
        usort($usableOrientations, $sorter);
93
94
        $this->logger->debug('Selected best fit orientation', ['orientation' => $usableOrientations[0]]);
95 72
96 72
        return $usableOrientations[0];
97 72
    }
98
99 72
    /**
100
     * Find all possible orientations for an item.
101 72
     *
102
     * @return OrientatedItem[]
103
     */
104
    public function getPossibleOrientations(
105
        Item $item,
106
        ?OrientatedItem $prevItem,
107
        int $widthLeft,
108
        int $lengthLeft,
109 72
        int $depthLeft,
110
        int $x,
111
        int $y,
112
        int $z,
113
        PackedItemList $prevPackedItemList
114
    ): array {
115
        $permutations = $this->generatePermutations($item, $prevItem);
116
117
        //remove any that simply don't fit
118
        $orientations = [];
119
        foreach ($permutations as $dimensions) {
120 72
            if ($dimensions[0] <= $widthLeft && $dimensions[1] <= $lengthLeft && $dimensions[2] <= $depthLeft) {
121
                $orientations[] = new OrientatedItem($item, $dimensions[0], $dimensions[1], $dimensions[2]);
122
            }
123 72
        }
124 72
125 72
        if ($item instanceof ConstrainedPlacementItem && !$this->box instanceof WorkingVolume) {
126 72
            $orientations = array_filter($orientations, function (OrientatedItem $i) use ($x, $y, $z, $prevPackedItemList) {
127
                return $i->getItem()->canBePacked($this->box, $prevPackedItemList, $x, $y, $z, $i->getWidth(), $i->getLength(), $i->getDepth());
128
            });
129
        }
130 72
131 3
        return $orientations;
132 6
    }
133 6
134
    /**
135
     * @param  OrientatedItem[] $possibleOrientations
136 72
     * @return OrientatedItem[]
137
     */
138
    protected function getUsableOrientations(
139
        Item $item,
140
        array $possibleOrientations
141
    ): array {
142
        $stableOrientations = $unstableOrientations = [];
143
144
        // Divide possible orientations into stable (low centre of gravity) and unstable (high centre of gravity)
145
        foreach ($possibleOrientations as $orientation) {
146
            if ($orientation->isStable() || $this->box->getInnerDepth() === $orientation->getDepth()) {
147
                $stableOrientations[] = $orientation;
148
            } else {
149
                $unstableOrientations[] = $orientation;
150
            }
151
        }
152
153
        /*
154
         * We prefer to use stable orientations only, but allow unstable ones if
155
         * the item doesn't fit in the box any other way
156
         */
157
        if (count($stableOrientations) > 0) {
158
            return $stableOrientations;
159
        }
160
161
        if ((count($unstableOrientations) > 0) && !$this->hasStableOrientationsInEmptyBox($item)) {
162
            return $unstableOrientations;
163
        }
164
165
        return [];
166
    }
167
168
    /**
169
     * Return the orientations for this item if it were to be placed into the box with nothing else.
170
     */
171
    protected function hasStableOrientationsInEmptyBox(Item $item): bool
172
    {
173
        $cacheKey = $item->getWidth() .
174
            '|' .
175
            $item->getLength() .
176
            '|' .
177
            $item->getDepth() .
178
            '|' .
179 72
            ($item->getKeepFlat() ? '2D' : '3D') .
180
            '|' .
181
            $this->box->getInnerWidth() .
182
            '|' .
183 72
            $this->box->getInnerLength() .
184
            '|' .
185
            $this->box->getInnerDepth();
186 72
187 72
        if (isset(static::$emptyBoxStableItemOrientationCache[$cacheKey])) {
188 68
            return static::$emptyBoxStableItemOrientationCache[$cacheKey];
189
        }
190 18
191
        $orientations = $this->getPossibleOrientations(
192
            $item,
193
            null,
194
            $this->box->getInnerWidth(),
195
            $this->box->getInnerLength(),
196
            $this->box->getInnerDepth(),
197
            0,
198 72
            0,
199 68
            0,
200
            new PackedItemList()
201
        );
202 62
203 12
        $stableOrientations = array_filter(
204
            $orientations,
205
            static function (OrientatedItem $orientation) {
206 62
                return $orientation->isStable();
207
            }
208
        );
209
        static::$emptyBoxStableItemOrientationCache[$cacheKey] = count($stableOrientations) > 0;
210
211
        return static::$emptyBoxStableItemOrientationCache[$cacheKey];
212 18
    }
213
214 18
    private function generatePermutations(Item $item, ?OrientatedItem $prevItem): array
215 18
    {
216 18
        //Special case items that are the same as what we just packed - keep orientation
217 18
        if ($prevItem && $prevItem->isSameDimensions($item)) {
218 18
            return [[$prevItem->getWidth(), $prevItem->getLength(), $prevItem->getDepth()]];
219 18
        }
220 18
221 18
        $permutations = [];
222 18
        $w = $item->getWidth();
223 18
        $l = $item->getLength();
224 18
        $d = $item->getDepth();
225 18
226 18
        //simple 2D rotation
227
        $permutations[$w . $l . $d] = [$w, $l, $d];
228 18
        $permutations[$l . $w . $d] = [$l, $w, $d];
229 12
230
        //add 3D rotation if we're allowed
231
        if (!$item->getKeepFlat()) {
232 18
            $permutations[$w . $d . $l] = [$w, $d, $l];
233 18
            $permutations[$l . $d . $w] = [$l, $d, $w];
234 18
            $permutations[$d . $w . $l] = [$d, $w, $l];
235 18
            $permutations[$d . $l . $w] = [$d, $l, $w];
236 18
        }
237 18
238 18
        return $permutations;
239 18
    }
240
}
241