Passed
Push — 3.x ( ec426a...33350c )
by Doug
01:45
created

Packer::sanityPrecheck()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 7
c 0
b 0
f 0
nc 7
nop 0
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 5
rs 9.6111
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
        $packedBoxes = $this->doVolumePacking();
146
147
        //If we have multiple boxes, try and optimise/even-out weight distribution
148 36
        if ($packedBoxes->count() > 1 && $packedBoxes->count() <= $this->maxBoxesToBalanceWeight) {
149 16
            $redistributor = new WeightRedistributor($this->boxes, $this->boxesQtyAvailable);
150 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

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

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