本文整理汇总了PHP中SplQueue::count方法的典型用法代码示例。如果您正苦于以下问题:PHP SplQueue::count方法的具体用法?PHP SplQueue::count怎么用?PHP SplQueue::count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SplQueue
的用法示例。
在下文中一共展示了SplQueue::count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* Запуск в работу
*
* @param mixed $data данные для задачи
* @param bool $wait ожидание результата
*@return mixed результатs
*/
public function run($data = null, $wait = true)
{
// добавляем задачу
if ($data) {
$this->add($data);
}
// обработка
while ($this->_Messages->count()) {
$message = $this->_Messages->pop();
$this->_Channel->basic_publish($message, '', $this->_queue());
// массив запущенных задач
$this->_runtime[$message->get('correlation_id')] = time();
}
// если есть обработчик ответов, то слушаем его
if ($this->_cbQueue && $wait) {
if (method_exists($this, 'onResponse')) {
$this->_Channel->basic_consume($this->_cbQueue, '', false, true, false, false, [$this, 'onResponse']);
} else {
// если же метода нет, но подождать надо, то тут всё просто:
$this->_Channel->basic_consume($this->_cbQueue, '', false, true, false, false, function (AMQPMessage $Message) {
$response = $this->_decode($Message->body);
unset($this->_collerations[$Message->get('correlation_id')], $this->_runtime[$Message->get('correlation_id')]);
if ($response instanceof \Exception) {
throw $response;
}
return true;
});
}
// ждём
while (count($this->_collerations)) {
$this->_Channel->wait();
}
}
return true;
}
示例2: onExit
public function onExit($status)
{
if ($this->pendingRequests->count() > 0) {
$nextExpectedTest = $this->pendingRequests->dequeue();
$this->distributor->testCompleted($this, TestResult::errorFromRequest($nextExpectedTest, "Worker{$this->id} died\n{$this->testErr}"));
}
}
示例3: pop
/** @return Error|null */
public static function pop()
{
if (!self::$errors) {
return null;
}
return self::$errors->count() > 0 ? self::$errors->dequeue() : null;
}
示例4: __debugInfo
/**
* Dump promise state, result and number of callbacks.
*
* @return array
*/
public function __debugInfo() : array
{
static $states = [Awaitable::PENDING => 'PENDING', Awaitable::RESOLVED => 'RESOLVED', Awaitable::FAILED => 'FAILED'];
$info = \get_object_vars($this);
$info['state'] = $states[$this->state];
$info['callbacks'] = $this->callbacks ? $this->callbacks->count() : 0;
\ksort($info);
return $info;
}
示例5: run
/**
* Starts the event loop.
*/
public function run()
{
$timeout = 0;
while (!empty($this->future) && !$this->main->isFinished()) {
$this->waitForStreamActivity($timeout);
$this->nextTick();
$timeout = $this->tick->count() === 0 ? 1 : 0;
$this->tick();
}
}
示例6: shouldShutDownMessenger
protected function shouldShutDownMessenger(Messenger $messenger)
{
if ($this->callQueue->count() == 0 && $this->pool->count() > $this->options['min_size']) {
unset($this->coreMessengerMapping[spl_object_hash($messenger)]);
$this->pool->detach($messenger);
$messenger->softTerminate();
return;
}
$this->readyPool->enqueue($messenger);
}
示例7: releaseConnection
/**
* Once a connection has finished being used...
* @param Connection $connection
*/
public function releaseConnection(Connection $connection)
{
// If we have any promises waiting for the connection, pass it along.
if ($this->waiting->count() > 0) {
$cb = $this->waiting->dequeue();
$cb($connection);
return;
}
// Otherwise, move it to the idle queue.
$this->available->enqueue($connection);
}
示例8: filesystemResultHandler
/**
* @param callable $func
* @return callable
*/
protected function filesystemResultHandler(callable $func)
{
return function ($mixed) use($func) {
if ($this->callQueue->count() == 0) {
$this->callQueueActive = false;
} else {
$this->processQueue();
}
return $func($mixed);
};
}
示例9: processQueue
/**
* Process the Queue
*
* @throws \Exception
*/
public function processQueue()
{
if (!$this->getAllowMultipleRegistrations()) {
throw new \Exception("Queuing only allowed when there are multiple registrations");
}
// find the best candidate
while ($this->callQueue->count() > 0) {
$registration = NULL;
if (strcasecmp($this->getInvokeType(), Registration::FIRST_REGISTRATION) === 0) {
$registration = $this->getNextFirstRegistration();
} else {
if (strcasecmp($this->getInvokeType(), Registration::LAST_REGISTRATION) === 0) {
$registration = $this->getNextLastRegistration();
} else {
if (strcasecmp($this->getInvokeType(), Registration::RANDOM_REGISTRATION) === 0) {
$registration = $this->getNextRandomRegistration();
} else {
if (strcasecmp($this->getInvokeType(), Registration::ROUNDROBIN_REGISTRATION) === 0) {
$registration = $this->getNextRoundRobinRegistration();
} else {
if (strcasecmp($this->getInvokeType(), Registration::THRUWAY_REGISTRATION) === 0) {
$registration = $this->getNextThruwayRegistration();
}
}
}
}
}
if ($registration === NULL) {
break;
}
$call = $this->callQueue->dequeue();
$registration->processCall($call);
}
}
示例10: processQueue
/**
* Process the Queue
*
* @throws \Exception
*/
public function processQueue()
{
if (!$this->getAllowMultipleRegistrations()) {
throw new \Exception("queuing only allowed when there are multiple registrations");
}
// find the best candidate
while ($this->callQueue->count() > 0) {
$congestion = true;
/* @var $bestRegistration \Thruway\Registration */
$bestRegistration = $this->registrations[0];
/* @var $registration \Thruway\Registration */
foreach ($this->registrations as $registration) {
if ($registration->getSession()->getPendingCallCount() == 0) {
$bestRegistration = $registration;
$congestion = false;
break;
}
if ($registration->getSession()->getPendingCallCount() < $bestRegistration->getSession()->getPendingCallCount()) {
$bestRegistration = $registration;
}
}
if ($congestion) {
// there is congestion
$bestRegistration->getSession()->getRealm()->publishMeta('thruway.metaevent.procedure.congestion', [["name" => $this->getProcedureName()]]);
return;
}
$call = $this->callQueue->dequeue();
$bestRegistration->processCall($call);
}
}
示例11: bfs_path
function bfs_path($graph, $start, $end)
{
$queue = new SplQueue();
# Enqueue the path
$queue->enqueue([$start]);
$visited = [$start];
while ($queue->count() > 0) {
$path = $queue->dequeue();
# Get the last node on the path
# so we can check if we're at the end
$node = $path[sizeof($path) - 1];
if ($node === $end) {
return $path;
}
foreach ($graph[$node] as $neighbour) {
if (!in_array($neighbour, $visited)) {
$visited[] = $neighbour;
# Build new path appending the neighbour then and enqueue it
$new_path = $path;
$new_path[] = $neighbour;
$queue->enqueue($new_path);
}
}
}
return false;
}
示例12: processQueue
public function processQueue()
{
if ($this->commandQueue->count() == 0) {
return;
}
if ($this->connStatus === $this::CONNECTION_BAD) {
$this->failAllCommandsWith(new \Exception("Bad connection: " . $this->lastError));
$this->stream->end();
return;
}
while ($this->commandQueue->count() > 0 && $this->queryState === static::STATE_READY) {
/** @var CommandInterface $c */
$c = $this->commandQueue->dequeue();
$this->debug("Sending " . get_class($c));
if ($c instanceof Query) {
$this->debug("Sending simple query: " . $c->getQueryString());
}
$this->stream->write($c->encodedMessage());
if ($c instanceof Terminate) {
$this->stream->end();
}
if ($c->shouldWaitForComplete()) {
$this->queryState = $this::STATE_BUSY;
if ($c instanceof Query) {
$this->queryType = $this::QUERY_SIMPLE;
} elseif ($c instanceof Sync) {
$this->queryType = $this::QUERY_EXTENDED;
}
$this->currentCommand = $c;
return;
}
}
}
示例13: initReadable
/** @internal */
private function initReadable()
{
$this->readBuffer = new \SplQueue();
$this->on('__listenersChanged', function () {
$this->hasDataListeners = 0 != count($this->listeners('data'));
if (!$this->paused) {
$this->resume();
}
});
$this->registerPersistentEvents('end', 'error');
$this->pushFn = function ($object, callable $onFlush = null) : bool {
if (null === $object) {
$this->endRead();
return false;
}
$readBufferEmpty = $this->readBuffer->isEmpty();
if ($this->paused || !$this->hasDataListeners) {
$this->readBuffer->enqueue([$object, $onFlush]);
if ($readBufferEmpty) {
$this->emit('readable');
}
} elseif (!$readBufferEmpty) {
// not paused but buffer has items - must be within resume()
$this->readBuffer->enqueue([$object, $onFlush]);
} else {
$this->emitData($object, $onFlush);
}
return $this->readBuffer->count() < $this->highWaterMark;
};
}
示例14: render
protected function render(Func $func)
{
if (null !== $func->cfg) {
$this->enqueueBlock($func->cfg);
}
$renderedOps = new \SplObjectStorage();
$renderedBlocks = new \SplObjectStorage();
while ($this->blockQueue->count() > 0) {
$block = $this->blockQueue->dequeue();
$ops = [];
if ($block === $func->cfg) {
foreach ($func->params as $param) {
$renderedOps[$param] = $ops[] = $this->renderOp($param);
}
}
foreach ($block->phi as $phi) {
$result = $this->indent($this->renderOperand($phi->result) . " = Phi(");
$result .= implode(', ', array_map([$this, 'renderOperand'], $phi->vars));
$result .= ')';
$renderedOps[$phi] = $ops[] = ["op" => $phi, "label" => $result, "childBlocks" => []];
}
foreach ($block->children as $child) {
$renderedOps[$child] = $ops[] = $this->renderOp($child);
}
$renderedBlocks[$block] = $ops;
}
$varIds = $this->varIds;
$blockIds = $this->blocks;
$this->reset();
return ["blocks" => $renderedBlocks, "ops" => $renderedOps, "varIds" => $varIds, "blockIds" => $blockIds];
}
示例15: main
/**
* Copies for the audits and audits_logs table into the elastic search storage.
*
* @return bool
*/
public function main()
{
$table = $this->loadModel('Audits');
$table->hasMany('AuditDeltas');
$table->schema()->columnType('created', 'string');
$map = [];
$meta = [];
$featureList = function ($element) {
list($k, $v) = explode(':', $element);
(yield $k => $v);
};
if (!empty($this->params['type-map'])) {
$map = explode(',', $this->params['type-map']);
$map = collection($map)->unfold($featureList)->toArray();
}
if (!empty($this->params['extra-meta'])) {
$meta = explode(',', $this->params['extra-meta']);
$meta = collection($meta)->unfold($featureList)->toArray();
}
$from = (new Time($this->params['from']))->modify('midnight');
$until = (new Time($this->params['until']))->modify('23:59:59');
$currentId = null;
$buffer = new \SplQueue();
$buffer->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
$queue = new \SplQueue();
$queue->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
$index = ConnectionManager::get('auditlog_elastic')->getConfig('index');
$eventsFormatter = function ($audit) use($index, $meta) {
return $this->eventFormatter($audit, $index, $meta);
};
$changesExtractor = [$this, 'changesExtractor'];
$query = $table->find()->where(function ($exp) use($from, $until) {
return $exp->between('Audits.created', $from, $until, 'datetime');
})->where(function ($exp) {
if (!empty($this->params['exclude-models'])) {
$exp->notIn('Audits.model', explode(',', $this->params['exclude-models']));
}
if (!empty($this->params['models'])) {
$exp->in('Audits.model', explode(',', $this->params['models']));
}
return $exp;
})->matching('AuditDeltas')->order(['Audits.created', 'AuditDeltas.audit_id'])->bufferResults(false)->hydrate(false)->unfold(function ($audit) use($buffer, &$currentId) {
if ($currentId && $currentId !== $audit['id']) {
(yield collection($buffer)->toList());
}
$currentId = $audit['id'];
$buffer->enqueue($audit);
})->map($changesExtractor)->map($eventsFormatter)->unfold(function ($audit) use($queue) {
$queue->enqueue($audit);
if ($queue->count() >= 50) {
(yield collection($queue)->toList());
}
});
$query->each([$this, 'persistBulk']);
// There are probably some un-yielded results, let's flush them
$rest = collection(count($buffer) ? [collection($buffer)->toList()] : [])->map($changesExtractor)->map($eventsFormatter)->append($queue);
$this->persistBulk($rest->toList());
return true;
}