/** * 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); }
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; }
/** * {@inheritdoc} */ public function enqueue(Task $task) : \Generator { if (!$this->context->isRunning()) { throw new StatusError('The worker has not been started.'); } if ($this->shutdown) { throw new StatusError('The worker has been shut down.'); } // If the worker is currently busy, store the task in a busy queue. if (null !== $this->active) { $delayed = new Delayed(); $this->busyQueue->enqueue($delayed); (yield $delayed); } $this->active = new Coroutine($this->send($task)); try { $result = (yield $this->active); } catch (\Throwable $exception) { $this->kill(); throw new WorkerException('Sending the task to the worker failed.', $exception); } finally { $this->active = null; } // We're no longer busy at the moment, so dequeue a waiting task. if (!$this->busyQueue->isEmpty()) { $this->busyQueue->dequeue()->resolve(); } if ($result instanceof TaskFailure) { throw $result->getException(); } return $result; }
/** * @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]); }
/** * @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; }
/** * @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(); } }
/** * Adds an element to the queue * @param mixed $value */ public function enqueue($value) { $hash = $this->generateHash($value); if (!$this->hashes->in($hash)) { $this->hashes->append($hash); $this->queue->enqueue($value); $this->queue->rewind(); } }
/** * @return \React\Promise\PromiseInterface */ public function open() { if ($this->current < $this->limit) { $this->current++; return new FulfilledPromise(); } $deferred = new Deferred(); $this->promises->enqueue($deferred); return $deferred->promise(); }
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); }
public static function push($msg, $code = self::GENERIC_ERROR, $severity = self::SEVERITY_ERROR) { self::init(); self::$errors->enqueue(new Error($msg, $code, $severity)); if ($severity == self::SEVERITY_ERROR) { self::$logger->error($msg); } else { self::$logger->warn($msg); } }
/** * * Adds a route to the router * * @param $callable * @param $conditions * @author Tim Perry */ public function addRoute($callable, $conditions) { $route = clone $this->routePrototype; $route->setCallable($callable); if (!is_array($conditions)) { $conditions = array($conditions); } $route->addConditionsFromArray($this->replaceFilterFunctions($conditions)); $this->routes->enqueue($route); }
/** * @inheritDoc */ public function getQuery(Driver $driver, $link) { if (!$this->pool->contains($link)) { throw new \OutOfBoundsException(sprintf('Undefined %s in the pooling controller.', $driver->info($link))); } if (!$this->waiting->isEmpty()) { return $this->waiting->dequeue(); } $this->idle->enqueue($link); }
/** * 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); }
public function run(TestRequest $test) { if (!$this->process->isRunning()) { $this->process->stop(); $this->process->start(); } $this->debug("Added " . $test->encode()); $this->testErr = ''; $this->pendingRequests->enqueue($test); $this->process->write($test->encode()); }
/** * {@inheritdoc} */ public function start() { if (isset($this->deferred)) { throw new \RuntimeException('Tasks is already started'); } $this->deferred = new Deferred(); $this->process->start(function () { $this->outputBuffer->enqueue(func_get_args()); }); return $this->deferred->promise(); }
/** * Adds conditions to the route from the given array * * @param array $conditions - an array of conditions * * @throws \InvalidArgumentException * @author Tim Perry */ public function addConditionsFromArray(array $conditions) { foreach ($conditions as $condition) { if (!is_callable($condition)) { $message = "One or more of the conditions you provided are not callable, "; $message .= "please pass an array of callable functions."; throw new \InvalidArgumentException($message); } $this->conditions->enqueue($condition); } }
private function nextTick() { $this->future->rewind(); while ($this->future->valid() && ($task = $this->future->current())) { if (!$task->isBlocked() || !$task->isStarted()) { $this->tick->enqueue($task); $this->future->offsetUnset($this->future->key()); $this->future->prev(); } $this->future->next(); } }
/** * @param string $function * @param array $args * @param int $errorResultCode * @return \React\Promise\PromiseInterface */ public function invokeCall($function, $args, $errorResultCode = -1) { $this->callQueueActive = true; $deferred = new Deferred(); $this->callQueue->enqueue(new QueuedCall($deferred, $function, $args, $errorResultCode)); if (!$this->callQueue->isEmpty() && $this->runningOperations < $this->maxSimultaneousOperations) { $this->processQueue(); } return $deferred->promise()->then(function ($data) { return $this->adapter->callFilesystem($data['function'], $data['args'], $data['errorResultCode'])->then($this->filesystemResultHandler('React\\Promise\\resolve'), $this->filesystemResultHandler('React\\Promise\\reject')); }); }
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)); } } } }
/** * run main loop * * @param null $limit */ public function run($limit = null) { do { $start = microtime(true); foreach ($this->getDequeuedWatcher() as $watcher) { switch ($watcher->getState()) { case $watcher::STATE_ACTIVE: if ($watcher::STATE_FINISHED !== $watcher()) { $this->queue->enqueue($watcher); } break; case $watcher::STATE_STOPPED: $this->queue->enqueue($watcher); break; } } if (0 > ($sleep = $this->min - (microtime(true) - $start) * 1000000)) { $sleep = abs($sleep) % $this->min; } usleep($sleep); $this->ticks++; if ($this->ticks % 100) { gc_collect_cycles(); } if (!is_null($limit) && $limit <= $this->ticks) { break; } } while ($this->hasActiveWatchers() && $this->stop === false); }
/** * Add middleware to the pipe-line. Please note that middleware's will * be called in the order they are added. * * A middleware CAN implement the Middleware Interface, but MUST be * callable. A middleware WILL be called with three parameters: * Request, Response and Next. * * @throws \RuntimeException when adding middleware to the stack to late * @param callable $middleware */ public function pipe(callable $middleware) { // Check if the pipeline is locked if ($this->locked) { throw new \RuntimeException('Middleware can’t be added once the stack is dequeuing'); } // Inject the dependency injection container if (method_exists($middleware, 'setContainer') && $this->container !== null) { $middleware->setContainer($this->container); } // Force serializers to register mime types if ($middleware instanceof SerializerMiddleware) { $middleware->registerMimeTypes(); } // Add the middleware to the queue $this->queue->enqueue($middleware); // Check if middleware should be added to the error queue if (!$this->errorQueueLocked) { $this->errorQueue->enqueue($middleware); // Check if we should lock the error queue if ($middleware instanceof ErrorMiddleware) { $this->errorQueueLocked = true; } } }
/** * * @throws Response\Exception * @return Response\Response */ protected function _getResponse() { $version = unpack('C', $this->_node->read(1))[1]; switch ($version) { case 0x83: $header = unpack('Cflags/nstream/Copcode/Nlength', $this->_node->read(8)); $body = $header['length'] === 0 ? '' : $this->_node->read($header['length']); static $responseClassMap = [Frame::OPCODE_ERROR => 'Cassandra\\Response\\Error', Frame::OPCODE_READY => 'Cassandra\\Response\\Ready', Frame::OPCODE_AUTHENTICATE => 'Cassandra\\Response\\Authenticate', Frame::OPCODE_SUPPORTED => 'Cassandra\\Response\\Supported', Frame::OPCODE_RESULT => 'Cassandra\\Response\\Result', Frame::OPCODE_EVENT => 'Cassandra\\Response\\Event', Frame::OPCODE_AUTH_SUCCESS => 'Cassandra\\Response\\AuthSuccess']; if (!isset($responseClassMap[$header['opcode']])) { throw new Response\Exception('Unknown response'); } $responseClass = $responseClassMap[$header['opcode']]; $response = new $responseClass($header, new Response\StreamReader($body)); if ($header['stream'] !== 0) { if (isset($this->_statements[$header['stream']])) { $this->_statements[$header['stream']]->setResponse($response); unset($this->_statements[$header['stream']]); $this->_recycledStreams->enqueue($header['stream']); } elseif ($response instanceof Response\Event) { $this->trigger($response); } } return $response; default: throw new Exception('php-cassandra supports CQL binary protocol v3 only, please upgrade your Cassandra to 2.1 or later.'); } }
/** * Process the given queue of template files and * returns the generated output. * * @param string $file * * @return string * @throws RendererException */ public function render(string $file) : string { if ($this->rendering) { throw new RendererException("Cannot call render() inside templates."); } $this->rendering = true; $this->queue->enqueue($file); $this->sections()->declare('content'); ob_start(); while (!$this->queue->isEmpty()) { $file = $this->engine->path($this->queue->dequeue()); if (!file_exists($file)) { throw new \RuntimeException("Cannot find file: {$file}"); } require $file; $this->sections()->populate('content', ob_get_contents(), 'replace'); ob_clean(); if ($this->extended) { $this->extended = false; } } ob_end_clean(); $this->rendering = false; return $this->sections()->fetch('content'); }
/** * Receive a value from the channel. * * Be careful when you may receive null values: you need to change the EOF param accordingly! * * @param mixed $eof The EOF value, a channel will return this value if it has been closed without an error. * @return mixed The received value. * * @throws \Throwable Fails if the channel has been closed with an error. */ public function receive($eof = null) : Awaitable { if (!$this->buffer) { while ($this->senders && !$this->senders->isEmpty()) { $subscription = $this->senders->dequeue(); if ($subscription->active) { $subscription->resolve($subscription->data); return new Success($subscription->data); } } } elseif (!$this->buffer->isEmpty()) { while ($this->senders && !$this->senders->isEmpty()) { $subscription = $this->senders->dequeue(); if ($subscription->active) { $subscription->resolve($subscription->data); $this->buffer->push($subscription->data); } } return new Success($this->buffer->dequeue()); } if ($this->closed instanceof \Throwable) { return new Failure($this->closed); } elseif ($this->closed) { return new Success($eof); } if (!$this->receivers) { $this->receivers = new \SplQueue(); } $this->receivers->enqueue($subscription = new ChannelSubscription($eof)); return $subscription; }
protected function enqueueBlock(Block $block) { if (!$this->blocks->contains($block)) { $this->blocks[$block] = count($this->blocks) + 1; $this->blockQueue->enqueue($block); } }
/** * 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); } }
/** * 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); }
/** @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; }; }
/** * * @throws Response\Exception * @return Response\Response */ protected function _getResponse() { $header = unpack('Cversion/Cflags/nstream/Copcode/Nlength', $this->fetchData(9)); if ($header['length']) { $body = $this->fetchData($header['length']); } else { $body = ''; } static $responseClassMap = array(Frame::OPCODE_ERROR => 'Cassandra\\Response\\Error', Frame::OPCODE_READY => 'Cassandra\\Response\\Ready', Frame::OPCODE_AUTHENTICATE => 'Cassandra\\Response\\Authenticate', Frame::OPCODE_SUPPORTED => 'Cassandra\\Response\\Supported', Frame::OPCODE_RESULT => 'Cassandra\\Response\\Result', Frame::OPCODE_EVENT => 'Cassandra\\Response\\Event', Frame::OPCODE_AUTH_SUCCESS => 'Cassandra\\Response\\AuthSuccess'); if (!isset($responseClassMap[$header['opcode']])) { throw new Response\Exception('Unknown response'); } $responseClass = $responseClassMap[$header['opcode']]; $response = new $responseClass($header, $body); if ($header['stream'] !== 0) { if (isset($this->_statements[$header['stream']])) { $this->_statements[$header['stream']]->setResponse($response); unset($this->_statements[$header['stream']]); $this->_recycledStreams->enqueue($header['stream']); } elseif ($response instanceof Response\Event) { $this->trigger($response); } } return $response; }
/** * @param TaskListPosition $taskListPosition * @param WorkflowMessage|LogMessage $lastAnswer * @throws \RuntimeException If process cannot be found * @throws \Exception If error occurs during processing */ private function continueProcessAt(TaskListPosition $taskListPosition, $lastAnswer) { $process = $this->processRepository->get($taskListPosition->taskListId()->processId()); if (is_null($process)) { throw new \RuntimeException(sprintf("Last received message %s (%s) contains unknown processId. A process with id %s cannot be found!", $lastAnswer->getMessageName(), $lastAnswer->uuid()->toString(), $taskListPosition->taskListId()->processId()->toString())); } $this->beginTransaction(); try { $process->receiveMessage($lastAnswer, $this->workflowEngine); $this->commitTransaction(); } catch (\Exception $ex) { $this->rollbackTransaction(); throw $ex; } if ($process->isFinished()) { $this->processorEventQueue->enqueue($this->events()->getNewActionEvent('process_did_finish', $this, ['process_id' => $process->processId()->toString(), 'finished_at' => $lastAnswer->createdAt()->format(\DateTime::ISO8601), 'succeed' => $process->isSuccessfulDone()])); } if ($process->isSubProcess() && $process->isFinished()) { if ($process->isSuccessfulDone()) { $this->informParentProcessAboutSubProcess($process, true, $lastAnswer); } else { if (!$lastAnswer instanceof LogMessage) { $lastAnswer = LogMessage::logException(new \RuntimeException("Sub process failed but last message was not a LogMessage"), $process->parentTaskListPosition()); } if (!$lastAnswer->isError()) { $lastAnswer = LogMessage::logErrorMsg($lastAnswer->technicalMsg(), $lastAnswer); } $this->informParentProcessAboutSubProcess($process, false, $lastAnswer); } } }