*/ class WeightStrategy implements SelectorStrategyInterface, LoggerAwareInterface { use LoggerAwareTrait; use PhpSerializeStateless; /** * @inheritdoc */ public function pickNextTask(array $queues) { $pickedQueue = $this->pickQueueByWight($queues); $this->logDebug('Queue "' . strtoupper($pickedQueue->getName()) . '" picked by WeightStrategy'); return $pickedQueue->dequeue(); } /** * @return int */ public function getWaitTime() { return 1; } /** * Picks randomly a queue based on weight. * * For example, an array like ['A'=>5, 'B'=>45, 'C'=>50] means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%. * The values are simply relative to each other. If one value weight was 2, and the other weight of 1, * the value with the weight of 2 has about a 66% chance of being selected. * * @inheritdoc */ private function pickQueueByWight(array $queues) { $weights = array_map(function (QueueInterface $queue) { return $queue->getWeight(); }, $queues); $rand = mt_rand(1, array_sum($weights)); /** @var QueueInterface $queue */ foreach ($queues as $queue) { $rand -= $queue->getWeight(); if ($rand <= 0) { return $queue; } } } }