本文整理汇总了PHP中SplQueue类的典型用法代码示例。如果您正苦于以下问题:PHP SplQueue类的具体用法?PHP SplQueue怎么用?PHP SplQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SplQueue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: translate
/**
* Translate array sequence of tokens from infix to
* Reverse Polish notation (RPN) which representing mathematical expression.
*
* @param array $tokens Collection of Token intances
* @return array Collection of Token intances
* @throws InvalidArgumentException
*/
public function translate(array $tokens)
{
$this->operatorStack = new SplStack();
$this->outputQueue = new SplQueue();
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
switch ($token->getType()) {
case Token::T_OPERAND:
$this->outputQueue->enqueue($token);
break;
case Token::T_OPERATOR:
case Token::T_FUNCTION:
$o1 = $token;
$isUnary = $this->isPreviousTokenOperator($tokens, $i) || $this->isPreviousTokenLeftParenthesis($tokens, $i) || $this->hasPreviousToken($i) === false;
if ($isUnary) {
if ($o1->getValue() === '-' || $o1->getValue() === '+') {
$o1 = new Operator($o1->getValue() . 'u', 3, Operator::O_NONE_ASSOCIATIVE);
} else {
if (!$o1 instanceof FunctionToken) {
throw new \InvalidArgumentException("Syntax error: operator '" . $o1->getValue() . "' cannot be used as a unary operator or with an operator as an operand.");
}
}
} else {
while ($this->hasOperatorInStack() && ($o2 = $this->operatorStack->top()) && $o1->hasLowerPriority($o2)) {
$this->outputQueue->enqueue($this->operatorStack->pop());
}
}
$this->operatorStack->push($o1);
break;
case Token::T_LEFT_BRACKET:
$this->operatorStack->push($token);
break;
case Token::T_RIGHT_BRACKET:
if ($this->isPreviousTokenOperator($tokens, $i)) {
throw new \InvalidArgumentException('Syntax error: an operator cannot be followed by a right parenthesis.');
} elseif ($this->isPreviousTokenLeftParenthesis($tokens, $i)) {
throw new \InvalidArgumentException('Syntax error: empty parenthesis.');
}
while (!$this->operatorStack->isEmpty() && Token::T_LEFT_BRACKET != $this->operatorStack->top()->getType()) {
$this->outputQueue->enqueue($this->operatorStack->pop());
}
if ($this->operatorStack->isEmpty()) {
throw new \InvalidArgumentException('Syntax error: mismatched parentheses.');
}
$this->operatorStack->pop();
break;
default:
throw new \InvalidArgumentException(sprintf('Invalid token detected: %s.', $token));
break;
}
}
while ($this->hasOperatorInStack()) {
$this->outputQueue->enqueue($this->operatorStack->pop());
}
if (!$this->operatorStack->isEmpty()) {
throw new InvalidArgumentException('Syntax error: mismatched parentheses or misplaced number.');
}
return iterator_to_array($this->outputQueue);
}
示例2: log
/**
* @param $type
* @param $message
* @param null $data
*/
public function log($type, $message, $data = null)
{
if (!$this->traitErrorLog) {
$this->traitErrorLog = new \SplQueue();
}
$this->traitErrorLog->enqueue(['type' => $type, 'message' => $message, 'data' => $data]);
}
示例3: 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;
}
示例4: solve
/**
* Solve missionaries and cannibals problem.
*
* @return bool
*/
public function solve()
{
$initialState = new State(3, 3, 0, 0, 'left');
$initialNode = new Node($initialState, null, null);
if ($initialNode->state->isGoalState()) {
$this->displayNodeInfo($initialNode);
return true;
}
$queue = new SplQueue();
$queue->push($initialNode);
$explored = [];
while (true) {
if ($queue->isEmpty()) {
return false;
//nothing found
}
$node = $queue->pop();
$this->displayNodeInfo($node);
array_push($explored, $node->state);
if ($node->state->isGoalState()) {
return true;
}
//get all action and states available
$states = $node->state->getNextStates();
foreach ($states as $stateNode) {
if (!$stateNode->state->isValidState()) {
continue;
}
if (!in_array($stateNode->state, $explored)) {
$queue->push($stateNode);
}
}
}
}
示例5: when
/**
* Implements the when() method of the Promise interface.
*
* @param callable $onResolved
*/
public function when(callable $onResolved)
{
switch ($this->state) {
case Awaitable::RESOLVED:
try {
$onResolved(null, ...$this->result);
} catch (\Throwable $ex) {
Loop::defer(function () use($ex) {
throw $ex;
});
}
break;
case Awaitable::FAILED:
try {
$onResolved($this->result);
} catch (\Throwable $ex) {
Loop::defer(function () use($ex) {
throw $ex;
});
}
break;
default:
if (!$this->callbacks) {
$this->callbacks = new \SplQueue();
$this->callbacks->setIteratorMode(\SplQueue::IT_MODE_FIFO | \SplQueue::IT_MODE_DELETE);
}
$this->callbacks->enqueue($onResolved);
}
}
示例6: list_dependency_cycles
/**
* @return string[] names of any dependencies involved in dependency cycle[s] (or that depend
* upon those in the cycle)
*/
public function list_dependency_cycles()
{
$dep_counts = $this->dependency_counts();
$depends_on = $this->reverse_graph();
$deps_met_queue = new \SplQueue();
foreach ($dep_counts as $dependency => $count) {
if ($count === 0) {
$deps_met_queue->enqueue($dependency);
}
}
// Iteratively resolve dependencies
$num_removed = 0;
while (!$deps_met_queue->isEmpty()) {
$name = $deps_met_queue->dequeue();
$num_removed++;
if (!array_key_exists($name, $depends_on)) {
continue;
}
foreach ($depends_on[$name] as $dependant) {
$dep_counts[$dependant]--;
if ($dep_counts[$dependant] === 0) {
$deps_met_queue->enqueue($dependant);
}
}
}
// Find the dependencies that couldn't be resolved
$depends_on_cycle = [];
foreach ($dep_counts as $dependency => $count) {
if ($count > 0) {
$depends_on_cycle[] = $dependency;
}
}
return $depends_on_cycle;
}
示例7: shuntingYard
/**
* Re-order token stream into reverse polish notation.
*
* @param array $tokenList
*
* @return array of ComparatorVersions and logical operator tokens
*/
private function shuntingYard(array $tokenList)
{
$operatorStack = new \SplStack();
$output = new \SplQueue();
foreach ($tokenList as $token) {
// Accumulate Versions & Comparators
if ($token instanceof VersionRangeInterface) {
$output->enqueue($token);
// Handle operators
} elseif ($token instanceof Token) {
// Loop while the current token has higher precedence then the stack token
$operator1 = $token;
while ($this->hasOperator($operatorStack) && ($operator2 = $operatorStack->top()) && $this->hasLowerPrecedence($operator1, $operator2)) {
$output->enqueue($operatorStack->pop());
}
$operatorStack->push($operator1);
} else {
throw new \RuntimeException('Invalid version number');
}
}
// Merge remaining operators onto output list
while ($this->hasOperator($operatorStack)) {
$output->enqueue($operatorStack->pop());
}
return iterator_to_array($output);
}
示例8: 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;
}
示例9: executePipeline
/**
* {@inheritdoc}
*/
protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
{
while (!$commands->isEmpty()) {
$connection->writeRequest($commands->dequeue());
}
$connection->disconnect();
return array();
}
示例10: filterMetadataStack
private function filterMetadataStack(\SplDoublyLinkedList $metadataStack)
{
$filteredMetadataStack = new \SplQueue();
foreach ($metadataStack as $curProperty) {
if ($curProperty instanceof PropertyMetadata) {
$filteredMetadataStack->unshift($curProperty);
}
}
return $filteredMetadataStack;
}
示例11: writeItem
/**
* {@inheritdoc}
*/
public function writeItem(array $item)
{
$this->queue->push($item);
if (count($this->queue) >= $this->size) {
$this->flush();
}
}
示例12: 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;
}
示例13: getLoggedEvent
/**
* @return LogEvent
*/
public function getLoggedEvent() : LogEvent
{
if (!$this->hasLoggedEvents()) {
throw new \LogicException('No more events logged!');
}
return $this->logs->dequeue();
}
示例14: 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}"));
}
}
示例15: pop
/** @return Error|null */
public static function pop()
{
if (!self::$errors) {
return null;
}
return self::$errors->count() > 0 ? self::$errors->dequeue() : null;
}