本文整理汇总了PHP中SplQueue类的典型用法代码示例。如果您正苦于以下问题:PHP SplQueue类的具体用法?PHP SplQueue怎么用?PHP SplQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SplQueue类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
开发者ID:oat-sa,项目名称:lib-beeme,代码行数:67,代码来源:ShuntingYard.php
示例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]);
}
开发者ID:chilimatic,项目名称:database-component,代码行数:12,代码来源:ErrorLogTrait.php
示例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;
}
开发者ID:keevitaja,项目名称:bfs-php,代码行数:26,代码来源:bfs.php
示例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);
}
}
}
}
开发者ID:ankitpokhrel,项目名称:MissionariesAndCannibals-PHP,代码行数:39,代码来源:MissionariesAndCannibals.php
示例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);
}
}
开发者ID:koolkode,项目名称:async,代码行数:34,代码来源:AwaitableTrait.php
示例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;
}
开发者ID:thumbtack,项目名称:ttinjector,代码行数:38,代码来源:Graph.php
示例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);
}
开发者ID:ptlis,项目名称:semantic-version,代码行数:33,代码来源:LogicalOperatorProcessor.php
示例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;
}
开发者ID:lorenzo,项目名称:audit-stash,代码行数:64,代码来源:ElasticImportTask.php
示例9: executePipeline
/**
* {@inheritdoc}
*/
protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
{
while (!$commands->isEmpty()) {
$connection->writeRequest($commands->dequeue());
}
$connection->disconnect();
return array();
}
开发者ID:peterxiemin,项目名称:commonswoole,代码行数:11,代码来源:FireAndForget.php
示例10: filterMetadataStack
private function filterMetadataStack(\SplDoublyLinkedList $metadataStack)
{
$filteredMetadataStack = new \SplQueue();
foreach ($metadataStack as $curProperty) {
if ($curProperty instanceof PropertyMetadata) {
$filteredMetadataStack->unshift($curProperty);
}
}
return $filteredMetadataStack;
}
开发者ID:dspinellis,项目名称:pixelbonus,代码行数:10,代码来源:FieldsExclusionStrategy.php
示例11: testProvideQueueAsStartPoint
/**
* @covers Gliph\Traversal\DepthFirst::traverse
*/
public function testProvideQueueAsStartPoint()
{
extract($this->v);
$queue = new \SplQueue();
$queue->push($a);
$queue->push($e);
$this->g->addVertex($a);
$this->g->addVertex($e);
DepthFirst::traverse($this->g, new DepthFirstNoOpVisitor(), $queue);
}
开发者ID:anatalsceo,项目名称:en-classe,代码行数:13,代码来源:DepthFirstTest.php
示例12: testForValidValues
public function testForValidValues()
{
$var = new \SplQueue();
$var->push(1);
$var->push(2);
$var->push(3);
$data = new VariableWrapper(get_class($var), $var);
$result = $this->inspector->get($data);
$this->assertInstanceOf('Ladybug\\Plugin\\Extra\\Type\\CollectionType', $result);
$this->assertCount(3, $result);
}
开发者ID:raulfraile,项目名称:ladybug-plugin-extra,代码行数:11,代码来源:SplQueueTest.php
示例13: addRulesForPackage
protected function addRulesForPackage(PackageInterface $package)
{
$workQueue = new \SplQueue();
$workQueue->enqueue($package);
while (!$workQueue->isEmpty()) {
$package = $workQueue->dequeue();
if (isset($this->addedMap[$package->getId()])) {
continue;
}
$this->addedMap[$package->getId()] = true;
foreach ($package->getRequires() as $link) {
$possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
$this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
foreach ($possibleRequires as $require) {
$workQueue->enqueue($require);
}
}
foreach ($package->getConflicts() as $link) {
$possibleConflicts = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
foreach ($possibleConflicts as $conflict) {
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
}
}
$isInstalled = isset($this->installedMap[$package->getId()]);
foreach ($package->getReplaces() as $link) {
$obsoleteProviders = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
foreach ($obsoleteProviders as $provider) {
if ($provider === $package) {
continue;
}
if (!$this->obsoleteImpossibleForAlias($package, $provider)) {
$reason = $isInstalled ? Rule::RULE_INSTALLED_PACKAGE_OBSOLETES : Rule::RULE_PACKAGE_OBSOLETES;
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $provider, $reason, $link));
}
}
}
$obsoleteProviders = $this->pool->whatProvides($package->getName(), null);
foreach ($obsoleteProviders as $provider) {
if ($provider === $package) {
continue;
}
if ($package instanceof AliasPackage && $package->getAliasOf() === $provider) {
$this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package));
} elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) {
$reason = $package->getName() == $provider->getName() ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES;
$this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createConflictRule($package, $provider, $reason, $package));
}
}
}
}
开发者ID:itillawarra,项目名称:cmfive,代码行数:50,代码来源:RuleSetGenerator.php
示例14: writeItem
/**
* {@inheritdoc}
*/
public function writeItem(array $item)
{
$this->queue->push($item);
if (count($this->queue) >= $this->size) {
$this->flush();
}
}
开发者ID:portphp,项目名称:portphp,代码行数:10,代码来源:BatchWriter.php
示例15: 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;
}
开发者ID:pdedkov,项目名称:cakephp-rabbit,代码行数:42,代码来源:Producer.php
示例16: getLoggedEvent
/**
* @return LogEvent
*/
public function getLoggedEvent() : LogEvent
{
if (!$this->hasLoggedEvents()) {
throw new \LogicException('No more events logged!');
}
return $this->logs->dequeue();
}
开发者ID:algatux,项目名称:mongo-bundle,代码行数:10,代码来源:MongoLogger.php
示例17: 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}"));
}
}
开发者ID:vektah,项目名称:phpunit-parallel,代码行数:7,代码来源:WorkerTestExecutor.php
示例18: pop
/** @return Error|null */
public static function pop()
{
if (!self::$errors) {
return null;
}
return self::$errors->count() > 0 ? self::$errors->dequeue() : null;
}
开发者ID:Eygle,项目名称:INeedU,代码行数:8,代码来源:ErrorManager.class.php
示例19: __invoke
public function __invoke($id, $service)
{
if ($this->middlewares->isEmpty()) {
return $service;
}
$method = $this->middlewares->dequeue();
return call_user_func($method, $this->container, new Next($this->container, $this->middlewares), $id, $service);
}
开发者ID:mrferos,项目名称:GenieDi,代码行数:8,代码来源:Next.php
示例20: dispatch
/**
* @param EventInterface $event
* @param bool $asynchronously
*/
public function dispatch(EventInterface $event, $asynchronously = false)
{
if (!$asynchronously) {
$this->scope->emit($event->getName(), [$event]);
} else {
$this->queue->enqueue($event);
$this->run();
}
}
开发者ID:inisire,项目名称:framework,代码行数:13,代码来源:EventDispatcher.php
注:本文中的SplQueue类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论