Passed
Push — 3.x ( e58d28...ec426a )
by Doug
01:41
created

Packer   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Test Coverage

Coverage 99%

Importance

Changes 12
Bugs 0 Features 0
Metric Value
wmc 39
eloc 85
c 12
b 0
f 0
dl 0
loc 254
ccs 99
cts 100
cp 0.99
rs 9.28

14 Methods

Rating   Name   Duplication   Size   Complexity  
A setBoxes() 0 5 3
A setMaxBoxesToBalanceWeight() 0 3 1
A setBoxQuantity() 0 3 1
A addBox() 0 5 2
A getMaxBoxesToBalanceWeight() 0 3 1
A pack() 0 15 3
A compare() 0 12 3
A findBestBoxFromIteration() 0 9 2
A sanityPrecheck() 0 15 5
B doVolumePacking() 0 41 7
A getBoxList() 0 20 6
A __construct() 0 7 1
A setItems() 0 8 3
A addItem() 0 4 1
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_merge;
12
use function count;
13
use const PHP_INT_MAX;
14
use Psr\Log\LoggerAwareInterface;
15
use Psr\Log\LoggerAwareTrait;
16
use Psr\Log\LogLevel;
17
use Psr\Log\NullLogger;
18
use SplObjectStorage;
19
use function usort;
20
21
/**
22
 * Actual packer.
23
 *
24
 * @author Doug Wright
25
 */
26
class Packer implements LoggerAwareInterface
27
{
28
    use LoggerAwareTrait;
29
30
    /**
31
     * Number of boxes at which balancing weight is deemed not worth it.
32
     *
33
     * @var int
34
     */
35
    protected $maxBoxesToBalanceWeight = 12;
36
37
    /**
38
     * List of items to be packed.
39
     *
40
     * @var ItemList
41
     */
42
    protected $items;
43
44
    /**
45
     * List of box sizes available to pack items into.
46
     *
47
     * @var BoxList
48
     */
49
    protected $boxes;
50
51
    /**
52
     * Quantities available of each box type.
53
     *
54
     * @var SplObjectStorage
55
     */
56
    protected $boxesQtyAvailable;
57
58
    /**
59
     * Constructor.
60
     */
61 44
    public function __construct()
62
    {
63 44
        $this->items = new ItemList();
64 44
        $this->boxes = new BoxList();
65 44
        $this->boxesQtyAvailable = new SplObjectStorage();
66
67 44
        $this->logger = new NullLogger();
68 44
    }
69
70
    /**
71
     * Add item to be packed.
72
     */
73 42
    public function addItem(Item $item, int $qty = 1): void
74
    {
75 42
        $this->items->insert($item, $qty);
76 42
        $this->logger->log(LogLevel::INFO, "added {$qty} x {$item->getDescription()}", ['item' => $item]);
0 ignored issues
show
Bug introduced by
The method log() 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

76
        $this->logger->/** @scrutinizer ignore-call */ 
77
                       log(LogLevel::INFO, "added {$qty} x {$item->getDescription()}", ['item' => $item]);

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...
77 42
    }
78
79
    /**
80
     * Set a list of items all at once.
81
     * @param iterable|Item[] $items
82
     */
83 6
    public function setItems(iterable $items): void
84
    {
85 6
        if ($items instanceof ItemList) {
86
            $this->items = clone $items;
87
        } else {
88 6
            $this->items = new ItemList();
89 6
            foreach ($items as $item) {
90 6
                $this->items->insert($item);
91
            }
92
        }
93 6
    }
94
95
    /**
96
     * Add box size.
97
     */
98 40
    public function addBox(Box $box): void
99
    {
100 40
        $this->boxes->insert($box);
101 40
        $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
102 40
        $this->logger->log(LogLevel::INFO, "added box {$box->getReference()}", ['box' => $box]);
103 40
    }
104
105
    /**
106
     * Add a pre-prepared set of boxes all at once.
107
     */
108 6
    public function setBoxes(BoxList $boxList): void
109
    {
110 6
        $this->boxes = $boxList;
111 6
        foreach ($this->boxes as $box) {
112 6
            $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
113
        }
114 6
    }
115
116
    /**
117
     * Set the quantity of this box type available.
118
     */
119 40
    public function setBoxQuantity(Box $box, int $qty): void
120
    {
121 40
        $this->boxesQtyAvailable[$box] = $qty;
122 40
    }
123
124
    /**
125
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
126
     */
127 2
    public function getMaxBoxesToBalanceWeight(): int
128
    {
129 2
        return $this->maxBoxesToBalanceWeight;
130
    }
131
132
    /**
133
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
134
     */
135 6
    public function setMaxBoxesToBalanceWeight(int $maxBoxesToBalanceWeight): void
136
    {
137 6
        $this->maxBoxesToBalanceWeight = $maxBoxesToBalanceWeight;
138 6
    }
139
140
    /**
141
     * Pack items into boxes.
142
     */
143 42
    public function pack(): PackedBoxList
144
    {
145 42
        $this->sanityPrecheck();
146 38
        $packedBoxes = $this->doVolumePacking();
147
148
        //If we have multiple boxes, try and optimise/even-out weight distribution
149 36
        if ($packedBoxes->count() > 1 && $packedBoxes->count() <= $this->maxBoxesToBalanceWeight) {
150 16
            $redistributor = new WeightRedistributor($this->boxes, $this->boxesQtyAvailable);
151 16
            $redistributor->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\WeightRedistributor::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

151
            $redistributor->setLogger(/** @scrutinizer ignore-type */ $this->logger);
Loading history...
152 16
            $packedBoxes = $redistributor->redistributeWeight($packedBoxes);
153
        }
154
155 36
        $this->logger->log(LogLevel::INFO, "[PACKING COMPLETED], {$packedBoxes->count()} boxes");
156
157 36
        return $packedBoxes;
158
    }
159
160
    /**
161
     * Pack items into boxes using the principle of largest volume item first.
162
     *
163
     * @throws NoBoxesAvailableException
164
     */
165 38
    public function doVolumePacking(bool $singlePassMode = false, bool $enforceSingleBox = false): PackedBoxList
166
    {
167 38
        $packedBoxes = new PackedBoxList();
168
169
        //Keep going until everything packed
170 38
        while ($this->items->count()) {
171 38
            $packedBoxesIteration = [];
172
173
            //Loop through boxes starting with smallest, see what happens
174 38
            foreach ($this->getBoxList($enforceSingleBox) as $box) {
175 38
                $volumePacker = new VolumePacker($box, $this->items);
176 38
                $volumePacker->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\VolumePacker::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

176
                $volumePacker->setLogger(/** @scrutinizer ignore-type */ $this->logger);
Loading history...
177 38
                $volumePacker->setSinglePassMode($singlePassMode);
178 38
                $packedBox = $volumePacker->pack();
179 38
                if ($packedBox->getItems()->count()) {
180 38
                    $packedBoxesIteration[] = $packedBox;
181
182
                    //Have we found a single box that contains everything?
183 38
                    if ($packedBox->getItems()->count() === $this->items->count()) {
184 36
                        break;
185
                    }
186
                }
187
            }
188
189
            try {
190
                //Find best box of iteration, and remove packed items from unpacked list
191 38
                $bestBox = $this->findBestBoxFromIteration($packedBoxesIteration);
192 4
            } catch (NoBoxesAvailableException $e) {
193 4
                if ($enforceSingleBox) {
194 2
                    return new PackedBoxList();
195
                }
196 2
                throw $e;
197
            }
198
199 38
            $this->items->removePackedItems($bestBox->getItems());
200
201 38
            $packedBoxes->insert($bestBox);
202 38
            $this->boxesQtyAvailable[$bestBox->getBox()] = $this->boxesQtyAvailable[$bestBox->getBox()] - 1;
203
        }
204
205 36
        return $packedBoxes;
206
    }
207
208
    /**
209
     * Get a "smart" ordering of the boxes to try packing items into. The initial BoxList is already sorted in order
210
     * so that the smallest boxes are evaluated first, but this means that time is spent on boxes that cannot possibly
211
     * hold the entire set of items due to volume limitations. These should be evaluated first.
212
     */
213 38
    protected function getBoxList(bool $enforceSingleBox = false): iterable
214
    {
215 38
        $itemVolume = 0;
216 38
        foreach ($this->items as $item) {
217 38
            $itemVolume += $item->getWidth() * $item->getLength() * $item->getDepth();
218
        }
219
220 38
        $preferredBoxes = [];
221 38
        $otherBoxes = [];
222 38
        foreach ($this->boxes as $box) {
223 38
            if ($this->boxesQtyAvailable[$box] > 0) {
224 38
                if ($box->getInnerWidth() * $box->getInnerLength() * $box->getInnerDepth() >= $itemVolume) {
225 36
                    $preferredBoxes[] = $box;
226 10
                } elseif (!$enforceSingleBox) {
227 10
                    $otherBoxes[] = $box;
228
                }
229
            }
230
        }
231
232 38
        return array_merge($preferredBoxes, $otherBoxes);
233
    }
234
235
    /**
236
     * @param PackedBox[] $packedBoxes
237
     */
238 38
    protected function findBestBoxFromIteration(array $packedBoxes): PackedBox
239
    {
240 38
        if (count($packedBoxes) === 0) {
241 4
            throw new NoBoxesAvailableException("No boxes could be found for item '{$this->items->top()->getDescription()}'", $this->items->top());
242
        }
243
244 38
        usort($packedBoxes, [$this, 'compare']);
245
246 38
        return $packedBoxes[0];
247
    }
248
249 42
    private function sanityPrecheck(): void
250
    {
251
        /** @var Item $item */
252 42
        foreach ($this->items as $item) {
253 42
            $possibleFits = 0;
254
255
            /** @var Box $box */
256 42
            foreach ($this->boxes as $box) {
257 40
                if ($item->getWeight() <= ($box->getMaxWeight() - $box->getEmptyWeight())) {
258 40
                    $possibleFits += count((new OrientatedItemFactory($box))->getPossibleOrientationsInEmptyBox($item));
259
                }
260
            }
261
262 42
            if ($possibleFits === 0) {
263 4
                throw new ItemTooLargeException("Item '{$item->getDescription()}' is too large to fit into any box", $item);
264
            }
265
        }
266 38
    }
267
268 6
    private static function compare(PackedBox $boxA, PackedBox $boxB): int
269
    {
270 6
        $choice = $boxB->getItems()->count() <=> $boxA->getItems()->count();
271
272 6
        if ($choice === 0) {
273 6
            $choice = $boxB->getVolumeUtilisation() <=> $boxA->getVolumeUtilisation();
274
        }
275 6
        if ($choice === 0) {
276 6
            $choice = $boxB->getUsedVolume() <=> $boxA->getUsedVolume();
277
        }
278
279 6
        return $choice;
280
    }
281
}
282