Passed
Push — 3.x ( 539084...e58d28 )
by Doug
02:52
created

Packer::addItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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 29
    public function __construct()
62
    {
63 29
        $this->items = new ItemList();
64 29
        $this->boxes = new BoxList();
65 29
        $this->boxesQtyAvailable = new SplObjectStorage();
66
67 29
        $this->logger = new NullLogger();
68 29
    }
69
70
    /**
71
     * Add item to be packed.
72
     */
73 21
    public function addItem(Item $item, int $qty = 1): void
74
    {
75 21
        $this->items->insert($item, $qty);
76 21
        $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 21
    }
78
79
    /**
80
     * Set a list of items all at once.
81
     * @param iterable|Item[] $items
82
     */
83 10
    public function setItems(iterable $items): void
84
    {
85 10
        if ($items instanceof ItemList) {
86 7
            $this->items = clone $items;
87
        } else {
88 3
            $this->items = new ItemList();
89 3
            foreach ($items as $item) {
90 3
                $this->items->insert($item);
91
            }
92
        }
93 10
    }
94
95
    /**
96
     * Add box size.
97
     */
98 20
    public function addBox(Box $box): void
99
    {
100 20
        $this->boxes->insert($box);
101 20
        $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
102 20
        $this->logger->log(LogLevel::INFO, "added box {$box->getReference()}", ['box' => $box]);
103 20
    }
104
105
    /**
106
     * Add a pre-prepared set of boxes all at once.
107
     */
108 10
    public function setBoxes(BoxList $boxList): void
109
    {
110 10
        $this->boxes = $boxList;
111 10
        foreach ($this->boxes as $box) {
112 10
            $this->setBoxQuantity($box, $box instanceof LimitedSupplyBox ? $box->getQuantityAvailable() : PHP_INT_MAX);
113
        }
114 10
    }
115
116
    /**
117
     * Set the quantity of this box type available.
118
     */
119 27
    public function setBoxQuantity(Box $box, int $qty): void
120
    {
121 27
        $this->boxesQtyAvailable[$box] = $qty;
122 27
    }
123
124
    /**
125
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
126
     */
127 1
    public function getMaxBoxesToBalanceWeight(): int
128
    {
129 1
        return $this->maxBoxesToBalanceWeight;
130
    }
131
132
    /**
133
     * Number of boxes at which balancing weight is deemed not worth the extra computation time.
134
     */
135 3
    public function setMaxBoxesToBalanceWeight(int $maxBoxesToBalanceWeight): void
136
    {
137 3
        $this->maxBoxesToBalanceWeight = $maxBoxesToBalanceWeight;
138 3
    }
139
140
    /**
141
     * Pack items into boxes.
142
     */
143 28
    public function pack(): PackedBoxList
144
    {
145 28
        $this->sanityPrecheck();
146 26
        $packedBoxes = $this->doVolumePacking();
147
148
        //If we have multiple boxes, try and optimise/even-out weight distribution
149 25
        if ($packedBoxes->count() > 1 && $packedBoxes->count() <= $this->maxBoxesToBalanceWeight) {
150 9
            $redistributor = new WeightRedistributor($this->boxes, $this->boxesQtyAvailable);
151 9
            $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 9
            $packedBoxes = $redistributor->redistributeWeight($packedBoxes);
153
        }
154
155 25
        $this->logger->log(LogLevel::INFO, "[PACKING COMPLETED], {$packedBoxes->count()} boxes");
156
157 25
        return $packedBoxes;
158
    }
159
160
    /**
161
     * Pack items into boxes using the principle of largest volume item first.
162
     *
163
     * @throws NoBoxesAvailableException
164
     */
165 26
    public function doVolumePacking(bool $singlePassMode = false, bool $enforceSingleBox = false): PackedBoxList
166
    {
167 26
        $packedBoxes = new PackedBoxList();
168
169
        //Keep going until everything packed
170 26
        while ($this->items->count()) {
171 25
            $packedBoxesIteration = [];
172
173
            //Loop through boxes starting with smallest, see what happens
174 25
            foreach ($this->getBoxList($enforceSingleBox) as $box) {
175 25
                $volumePacker = new VolumePacker($box, $this->items);
176 25
                $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 25
                $volumePacker->setSinglePassMode($singlePassMode);
178 25
                $packedBox = $volumePacker->pack();
179 25
                if ($packedBox->getItems()->count()) {
180 25
                    $packedBoxesIteration[] = $packedBox;
181
182
                    //Have we found a single box that contains everything?
183 25
                    if ($packedBox->getItems()->count() === $this->items->count()) {
184 24
                        break;
185
                    }
186
                }
187
            }
188
189
            try {
190
                //Find best box of iteration, and remove packed items from unpacked list
191 25
                $bestBox = $this->findBestBoxFromIteration($packedBoxesIteration);
192 2
            } catch (NoBoxesAvailableException $e) {
193 2
                if ($enforceSingleBox) {
194 1
                    return new PackedBoxList();
195
                }
196 1
                throw $e;
197
            }
198
199 25
            $this->items->removePackedItems($bestBox->getItems());
200
201 25
            $packedBoxes->insert($bestBox);
202 25
            $this->boxesQtyAvailable[$bestBox->getBox()] = $this->boxesQtyAvailable[$bestBox->getBox()] - 1;
203
        }
204
205 25
        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 25
    protected function getBoxList(bool $enforceSingleBox = false): iterable
214
    {
215 25
        $itemVolume = 0;
216 25
        foreach ($this->items as $item) {
217 25
            $itemVolume += $item->getWidth() * $item->getLength() * $item->getDepth();
218
        }
219
220 25
        $preferredBoxes = [];
221 25
        $otherBoxes = [];
222 25
        foreach ($this->boxes as $box) {
223 25
            if ($this->boxesQtyAvailable[$box] > 0) {
224 25
                if ($box->getInnerWidth() * $box->getInnerLength() * $box->getInnerDepth() >= $itemVolume) {
225 24
                    $preferredBoxes[] = $box;
226 8
                } elseif (!$enforceSingleBox) {
227 8
                    $otherBoxes[] = $box;
228
                }
229
            }
230
        }
231
232 25
        return array_merge($preferredBoxes, $otherBoxes);
233
    }
234
235
    /**
236
     * @param PackedBox[] $packedBoxes
237
     */
238 25
    protected function findBestBoxFromIteration(array $packedBoxes): PackedBox
239
    {
240 25
        if (count($packedBoxes) === 0) {
241 2
            throw new NoBoxesAvailableException("No boxes could be found for item '{$this->items->top()->getDescription()}'", $this->items->top());
242
        }
243
244 25
        usort($packedBoxes, [$this, 'compare']);
245
246 25
        return $packedBoxes[0];
247
    }
248
249 28
    private function sanityPrecheck(): void
250
    {
251
        /** @var Item $item */
252 28
        foreach ($this->items as $item) {
253 28
            $possibleFits = 0;
254
255
            /** @var Box $box */
256 28
            foreach ($this->boxes as $box) {
257 27
                if ($item->getWeight() <= ($box->getMaxWeight() - $box->getEmptyWeight())) {
258 27
                    $possibleFits += count((new OrientatedItemFactory($box))->getPossibleOrientationsInEmptyBox($item));
259
                }
260
            }
261
262 28
            if ($possibleFits === 0) {
263 4
                throw new ItemTooLargeException("Item '{$item->getDescription()}' is too large to fit into any box", $item);
264
            }
265
        }
266 26
    }
267
268 4
    private static function compare(PackedBox $boxA, PackedBox $boxB): int
269
    {
270 4
        $choice = $boxB->getItems()->count() <=> $boxA->getItems()->count();
271
272 4
        if ($choice === 0) {
273 3
            $choice = $boxB->getVolumeUtilisation() <=> $boxA->getVolumeUtilisation();
274
        }
275 4
        if ($choice === 0) {
276 3
            $choice = $boxB->getUsedVolume() <=> $boxA->getUsedVolume();
277
        }
278
279 4
        return $choice;
280
    }
281
}
282