Exemplo n.º 1
1
 /**
  * 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);
 }
Exemplo n.º 2
0
 /**
  * @inheritdoc
  */
 public function pushHandler(HandlerInterface ...$handlers)
 {
     $this->initHandlers();
     foreach ($handlers as $handler) {
         $this->handlers->push($handler);
     }
 }
Exemplo n.º 3
0
 /**
  * Evaluate array sequence of tokens in Reverse Polish notation (RPN)
  * representing mathematical expression.
  * 
  * @param array $expressionTokens
  * @return float
  * @throws \InvalidArgumentException
  */
 private function evaluateRPN(array $expressionTokens)
 {
     $stack = new \SplStack();
     foreach ($expressionTokens as $token) {
         $tokenValue = $token->getValue();
         if (is_numeric($tokenValue)) {
             $stack->push((double) $tokenValue);
             continue;
         }
         switch ($tokenValue) {
             case '+':
                 $stack->push($stack->pop() + $stack->pop());
                 break;
             case '-':
                 $n = $stack->pop();
                 $stack->push($stack->pop() - $n);
                 break;
             case '*':
                 $stack->push($stack->pop() * $stack->pop());
                 break;
             case '/':
                 $n = $stack->pop();
                 $stack->push($stack->pop() / $n);
                 break;
             case '%':
                 $n = $stack->pop();
                 $stack->push($stack->pop() % $n);
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Invalid operator detected: %s', $tokenValue));
                 break;
         }
     }
     return $stack->top();
 }
Exemplo n.º 4
0
 /**
  * @inheritdoc
  */
 public function pushProcessor(ProcessorInterface ...$processors)
 {
     $this->initProcessors();
     foreach ($processors as $processor) {
         $this->processors->push($processor);
     }
 }
 public function startOrGroup()
 {
     $predicate = new OrPredicate(new NullPredicate());
     $this->predicateStack->top()->pushPredicate($predicate);
     $this->predicateStack->push($predicate);
     return $this;
 }
Exemplo n.º 6
0
 /**
  * 加载指定目录下的配置并生成[绝对路径=>配置]
  * (备用)
  *
  * @param        $filePath
  * @param string $ext
  */
 private function LoadV2($filePath, $ext = '.php')
 {
     $resConfig = [];
     $split = '.';
     if (file_exists($filePath)) {
         $key = basename($filePath, $ext);
         $configs = (include $filePath);
         $keyStack = new \SplStack();
         $keyStack->push([$key, $configs]);
         $whileCount = 0;
         //防止意外进入死循环,限制最多循环1024层
         while (!$keyStack->isEmpty() && $whileCount < 1024) {
             $whileCount++;
             $pair = $keyStack->pop();
             foreach ($pair[1] as $pairKey => $pairVal) {
                 if (is_array($pairVal)) {
                     $keyStack->push([$pair[0] . $split . $pairKey, $pairVal]);
                 } else {
                     $resConfig[$pair[0] . $split . $pairKey] = $pairVal;
                 }
             }
         }
     }
     return $resConfig;
 }
Exemplo n.º 7
0
 public function parse($data)
 {
     $tokens = $this->tokenizer($data);
     $this->stack = new \SplStack();
     $this->stack->push(0);
     while (true) {
         $token = $tokens[0];
         $state = $this->stack->top();
         $terminal = $token[0];
         if (!isset($this->action[$state][$terminal])) {
             throw new \Exception('Token not allowed here (' . $token[1] . ')');
         }
         $action = $this->action[$state][$terminal];
         if ($action[0] === 0) {
             $this->stack->push($token[1]);
             $this->stack->push($action[1]);
             array_shift($tokens);
         } elseif ($action[0] === 1) {
             $value = $this->reduce($action[2], $action[1]);
             array_unshift($tokens, array($action[3], $value));
         } elseif ($action[0] === 2) {
             $this->stack->pop();
             return $this->stack->pop();
         } else {
             throw new \RuntimeException('Cannot compile');
         }
     }
     throw new \RuntimeException('Cannot compile. EOF');
 }
Exemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 protected function onElementStart($parser, $name, $attributes)
 {
     $this->stack->push($name);
     if ($name === 'ITEM') {
         $this->currentRate = array();
     }
 }
Exemplo n.º 9
0
 function testPrintTraversable()
 {
     $stack = new \SplStack();
     $stack->push('foo');
     $stack->push('bar');
     $this->assertEquals("<SplStack>['bar', 'foo']", ValuePrinter::serialize($stack));
 }
Exemplo n.º 10
0
 public function registerCssFile($filename)
 {
     if (!isset($this->css_files)) {
         $this->css_files = new SplStack();
     }
     $this->css_files->push($filename);
 }
 public function calculate(array $variables)
 {
     $stack = new \SplStack();
     foreach ($this->reversePolandNotation as $token) {
         if ($token->getExpressionType() == ExpressionElementInterface::CONSTANT) {
             /** @var $token Constant */
             $stack->push($token->getValue());
         }
         if ($token->getExpressionType() == ExpressionElementInterface::VARIABLE) {
             /** @var $token Variable*/
             $variableName = $token->getValue();
             if (isset($variables[$variableName])) {
                 $stack->push($variables[$variableName]);
             } else {
                 throw new ExpressionParserException("Undefined variable: " . $variableName);
             }
         }
         if ($token->getExpressionType() == ExpressionElementInterface::OPERATOR) {
             /** @var $token OperatorInterface */
             $arg1 = $stack->pop();
             $arg2 = $stack->pop();
             $stack->push($token->calculate($arg1, $arg2));
         }
     }
     return $stack->top();
 }
 public function startVisiting($object)
 {
     if (!is_object($object)) {
         return;
     }
     $this->visitingSet->attach($object);
     $this->visitingStack->push($object);
 }
Exemplo n.º 13
0
 /**
  *  start profiling a block of code
  *  
  *  @param  string  $title  the name you are giving to this block of profiled code
  *  @return boolean pretty much always returns true
  */
 public function start($title)
 {
     $profile_map = array();
     $profile_map['start'] = microtime(true);
     $profile_map['title'] = $title;
     $this->stack_started->push($profile_map);
     return true;
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function withMiddleware($middleware) : StackContract
 {
     if ($middleware instanceof MiddlewareInterface || $middleware instanceof ServerMiddlewareInterface) {
         $this->stack->push($this->isContainerAware($middleware));
         return $this;
     }
     throw new LogicException('Unsupported middleware type.');
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function enterNode(Node $node)
 {
     if ($node instanceof Node\FunctionLike) {
         $this->loopStacks->push(new \SplStack());
     } elseif ($this->isTargetLoopNode($node)) {
         $this->getCurrentLoopStack()->push($node);
     }
 }
Exemplo n.º 16
0
 /**
  * @return self
  *
  * @throws \InvalidArgumentException Missing argument(s) when calling push
  */
 public function push()
 {
     if (func_num_args() === 0) {
         throw new \InvalidArgumentException("Missing argument(s) when calling push");
     }
     $spec = func_get_args();
     $this->specs->push($spec);
     return $this;
 }
Exemplo n.º 17
0
 /**
  * @return $this
  */
 public function push()
 {
     if (func_num_args() === 0) {
         throw new \InvalidArgumentException('Missing argument(s) when calling push');
     }
     $msgApp = func_get_args();
     $this->components->push($msgApp);
     return $this;
 }
Exemplo n.º 18
0
function postorder($tree)
{
    $lst = array();
    if (!$tree) {
        return $lst;
    }
    $stack = new SplStack();
    $stack->push($tree);
    $stack->rewind();
    $prev = null;
    while ($stack->valid()) {
        $curr = $stack->current();
        // go down the tree.
        //check if current node is leaf, if so, process it and pop stack,
        //otherwise, keep going down
        if (!$prev || @$prev->left->key == @$curr->key || @$prev->right->key == @$curr->key) {
            //prev == null is the situation for the root node
            if ($curr->left) {
                $stack->push($curr->left);
                $stack->rewind();
            } else {
                if ($curr->right) {
                    $stack->push($curr->right);
                    $stack->rewind();
                } else {
                    $stack->pop();
                    $stack->rewind();
                    $lst[] = $curr->key;
                }
            }
            //go up the tree from left node
            //need to check if there is a right child
            //if yes, push it to stack
            //otherwise, process parent and pop stack
        } else {
            if (@$curr->left->key == @$prev->key) {
                if (@$curr->right->key) {
                    $stack->push($curr->right);
                    $stack->rewind();
                } else {
                    $stack->pop();
                    $stack->rewind();
                    $lst[] = $curr->key;
                }
            } else {
                if (@$curr->right->key == @$prev->key) {
                    $stack->pop();
                    $stack->rewind();
                    $lst[] = $curr->key;
                }
            }
        }
        $prev = $curr;
    }
    return $lst;
}
Exemplo n.º 19
0
 public function getParamsStack()
 {
     if (null === $this->paramsStack) {
         $this->paramsStack = new \SplStack();
         if ($this->getParentCommand() instanceof CommandInterface) {
             $this->paramsStack->push($this->getParentCommand()->getParams());
         }
     }
     return $this->paramsStack;
 }
 public function testForValidValues()
 {
     $var = new \SplStack();
     $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);
 }
Exemplo n.º 21
0
 public function enterNode(Node $node)
 {
     if ($node instanceof Node\Stmt\Foreach_) {
         $this->checkNestedByReferenceForeach($node);
         $this->foreachStack->push($node);
     } elseif (!$this->foreachStack->isEmpty()) {
         $this->checkInternalArrayPointerAccessInByValueForeach($node);
         $this->checkArrayModificationByFunctionInByReferenceForeach($node);
         $this->checkAddingToArrayInByReferenceForeach($node);
     }
 }
Exemplo n.º 22
0
 public function getPathTo($endVertex)
 {
     if (!$this->hasPathTo($endVertex)) {
         return null;
     }
     $path = new \SplStack();
     for ($i = $endVertex; $i != $this->startVertex; $i = $this->edgeTo[$i]) {
         $path->push($i);
     }
     $path->push($this->startVertex);
     return $path;
 }
 public function enterNode(Node $node)
 {
     if ($node instanceof Node\Expr\Yield_) {
         $startTokenPosition = $node->getAttribute('startTokenPos');
         $endTokenPosition = $node->getAttribute('endTokenPos');
         if (!($this->tokenCollection->isTokenPrecededBy($startTokenPosition, '(') && $this->tokenCollection->isTokenFollowedBy($endTokenPosition, ')')) && !$this->expressionStack->isEmpty()) {
             $this->addContextMessage('"yield" usage in expression context', $this->expressionStack->top());
         }
     } elseif ($node instanceof Node\Expr) {
         $this->expressionStack->push($node);
     }
 }
Exemplo n.º 24
0
/**
 * Поиск самого дешёвого пути между двумя локациями
 * Для поиска используется алгоритм Дейкстры
 *
 * @see http://www.sitepoint.com/data-structures-4/
 *
 * @param array  $data   Массив с локациями и ценой проезда между ними [][src, dst, cost]
 * @param string $source Название исходного пункта
 * @param string $target Название конечного пункта
 *
 * @return SplStack
 */
function find_path(array $data, $source, $target)
{
    $graph = build_graph($data);
    // массив лучших цен кратчайшего пути для каждой локации
    $best_cost = [];
    // массив предыдущих локаций для каждой локации
    $prev_loc = array();
    // очередь из необработанных локаций
    $queue = new SplPriorityQueue();
    foreach ($graph as $src => $dst) {
        $best_cost[$src] = INF;
        // изначальные значения цен бесконечны
        $prev_loc[$src] = null;
        // предыдущие локации неизвестны
        foreach ($dst as $name => $cost) {
            // используем цену как приоритет в очереди
            $queue->insert($name, $cost);
        }
    }
    // цена поездки в исходный пункт = 0
    $best_cost[$source] = 0;
    while (!$queue->isEmpty()) {
        // получаем минимальную цену
        $u = $queue->extract();
        if (empty($graph[$u])) {
            continue;
        }
        // обрабатываем доступные маршруты для локации
        foreach ($graph[$u] as $v => $cost) {
            // альтернативная цена для маршрута
            $alt = $best_cost[$u] + $cost;
            if ($alt < $best_cost[$v]) {
                // обновляем минимальную цену для локации
                $best_cost[$v] = $alt;
                // добавляем локацию в массив предыдущих локаций
                $prev_loc[$v] = $u;
            }
        }
    }
    // ищем дешёвый путь и складываем его в стек
    $stack = new SplStack();
    $u = $target;
    $final_cost = 0;
    // проходим в обратном порядке от пункта назначения к исходному пункту
    while (isset($prev_loc[$u]) && $prev_loc[$u]) {
        $stack->push($u);
        $final_cost += $graph[$u][$prev_loc[$u]];
        $u = $prev_loc[$u];
    }
    $stack->push($source);
    return [$stack, $final_cost];
}
Exemplo n.º 25
0
 /**
  * Open given block if it is valid.
  *
  * @param string $name
  * @param array  $args
  */
 public function open($name, array $args = [])
 {
     if (!is_string($name)) {
         throw new InvalidArgumentException('Foil block name must be in a string.');
     }
     if (!array_key_exists($name, $this->blocks)) {
         throw new InvalidArgumentException("{$name} is not a registered Foil block.");
     }
     /** @var \Foil\Blocks\Block $buffer */
     $buffer = $this->blocks[$name];
     $buffer->open($args);
     $this->buffers->push([$buffer, $name]);
 }
Exemplo n.º 26
0
 /**
  *  get the current element
  *  
  *  this will push the current iterator on the stack if an array is found
  *  
  *  @return mixed
  */
 public function current()
 {
     $current = $this->iterator->current();
     if (is_array($current)) {
         $this->keys[] = $this->key();
         // move the iterator to the next element so it will be ready when it pops...
         $this->iterator->next();
         $this->stack->push($this->iterator);
         $this->iterator = new ArrayIterator($current);
         $current = $this->current();
     }
     //if
     return $current;
 }
 /**
  * @param null $class
  * @return void
  */
 public function disable($class = null)
 {
     if ($class !== null) {
         $this->classStack->push($class);
     }
     if ($this->entityManager->getFilters()->isEnabled('softdeleteable')) {
         if ($class !== null) {
             /** @var SoftDeleteableFilter $filter */
             $filter = $this->entityManager->getFilters()->getFilter('softdeleteable');
             $filter->disableForEntity($class);
         } else {
             $this->entityManager->getFilters()->disable('softdeleteable');
         }
     }
 }
Exemplo n.º 28
0
 /**
  * Pushes the specified form into the stack.
  *
  * @internal
  * @static
  * @param Opf_Form $form The form pushed to the stack.
  */
 public static function pushToStack(Opf_Form $form)
 {
     if (self::$_stack === null) {
         self::$_stack = new SplStack();
     }
     self::$_stack->push($form);
 }
Exemplo n.º 29
0
 /**
  * Run the pathfinder algorithm
  *
  * @return \SplStack
  */
 public function run()
 {
     $start = $this->start;
     $goal = $this->goal;
     $open = new Set([$start], function (NodeInterface $node) use($goal) {
         return $this->getHeuristic($goal, $node);
     });
     $closed = new Set();
     $open->add($start);
     $path = new \SplStack();
     $step = null;
     while (!$open->isEmpty()) {
         $current = $open->current();
         $path->push($current->getNode());
         $step = new Step($current->getNode(), $step);
         if ($current->getNode() == $goal) {
             break;
         }
         $closed->add($current->getNode());
         $neighbours = $current->getNode()->getNeighbours();
         foreach ($neighbours as $neighbour) {
             if ($closed->has($neighbour)) {
                 continue;
             }
             if (!$open->has($neighbour)) {
                 $open->add($neighbour, $this->getHeuristic($current->getNode(), $neighbour) + $neighbour->getCost());
             }
         }
     }
     return $path;
 }
Exemplo n.º 30
0
 public function providerForValidInput()
 {
     $ruleNotEmpty = new Each($this->getRuleMock(true));
     $ruleAlphaItemIntKey = new Each($this->getRuleMock(true), $this->getRuleMock(true));
     $ruleOnlyKeyValidation = new Each(null, $this->getRuleMock(true));
     $intStack = new \SplStack();
     $intStack->push(1);
     $intStack->push(2);
     $intStack->push(3);
     $intStack->push(4);
     $intStack->push(5);
     $stdClass = new \stdClass();
     $stdClass->name = 'Emmerson';
     $stdClass->age = 22;
     return [[$ruleNotEmpty, [1, 2, 3, 4, 5]], [$ruleNotEmpty, $intStack], [$ruleNotEmpty, $stdClass], [$ruleAlphaItemIntKey, ['a', 'b', 'c', 'd', 'e']], [$ruleOnlyKeyValidation, ['a', 'b', 'c', 'd', 'e']]];
 }