| Conditions | 9 |
| Paths | 11 |
| Total Lines | 51 |
| Code Lines | 25 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 19 | protected function fillPartitions(Partitions $partitions, Partition $dataset, int $chunks): void |
||
| 20 | { |
||
| 21 | // Edge case handling. |
||
| 22 | if ($dataset->count() === $chunks) { |
||
| 23 | foreach ($dataset as $key => $item) { |
||
| 24 | $partitions->partition((int) $key)->exchangeArray([$item]); |
||
| 25 | } |
||
| 26 | |||
| 27 | return; |
||
| 28 | } |
||
| 29 | |||
| 30 | // Edge case handling. |
||
| 31 | if (0 === $chunks) { |
||
| 32 | throw new \InvalidArgumentException('Chunks must be different from 0.'); |
||
| 33 | } |
||
| 34 | |||
| 35 | // Greedy needs a dataset sorted DESC. |
||
| 36 | $dataset->uasort( |
||
| 37 | static function (PartitionItem $left, PartitionItem $right) { |
||
| 38 | return $left->getWeight() <=> $right->getWeight(); |
||
| 39 | } |
||
| 40 | ); |
||
| 41 | |||
| 42 | $partitionsArray = []; |
||
| 43 | $best = $dataset->getWeight() / $chunks; |
||
| 44 | |||
| 45 | for ($p = 1; $p < $chunks; ++$p) { |
||
| 46 | $partition = $this->getPartitionFactory()::create(); |
||
| 47 | |||
| 48 | while ($partition->getWeight() < $best && 1 < $dataset->count()) { |
||
| 49 | $bounds = $dataset->getBounds(); |
||
| 50 | // Get the key of the item with the lowest value. |
||
| 51 | $key = $bounds[0]; |
||
| 52 | |||
| 53 | if (0 === $partition->count()) { |
||
| 54 | // Get the key of the item with the highest value. |
||
| 55 | $key = $bounds[1]; |
||
| 56 | } |
||
| 57 | |||
| 58 | $partition->append($dataset[$key]); |
||
| 59 | unset($dataset[$key]); |
||
| 60 | $dataset->exchangeArray(\array_values($dataset->getArrayCopy())); |
||
| 61 | } |
||
| 62 | |||
| 63 | $partitionsArray[] = $partition; |
||
| 64 | } |
||
| 65 | |||
| 66 | $partitionsArray[] = $dataset; |
||
| 67 | |||
| 68 | foreach ($partitionsArray as $key => $subset) { |
||
| 69 | $partitions->partition($key)->exchangeArray($subset); |
||
| 70 | } |
||
| 73 |