/** * Parse the ternary operator. * * @param Node $node The expression node. * @param int $precedence The precedence level. * @return Node The ternary operator node or the given expression node. * @throws SyntaxErrorException if no ternary else can be found after a ternary if. */ private function parseTernary(Node $node, $precedence) { /* @var Token $token */ while (($token = $this->stream->current()) && $this->operatorTable->isTernary($token)) { $operator = $this->operatorTable->getTernaryOperator($token); if ($operator->getIfCode() != $token->getCode() || $operator->getPrecedence() < $precedence) { break; } $operatorNode = $operator->getNode(); $subPrecedence = $operator->isRightAssociative() ? $operator->getPrecedence() : $operator->getPrecedence() + 1; // Parse the if expression if ($operator->isShorthandAllowed() && $this->stream->getLookaheadCode() == $operator->getElseCode()) { $this->stream->next(); $if = null; } else { $this->stream->next(); $if = $this->parseExpression($subPrecedence); } // Parse the else expression $this->stream->expect([$operator->getElseCode()], function (Token $current = null) { if ($current) { $near = substr($this->stream->getSource(), 0, $current->getOffset()); $message = "Ternary else expected; got `{$current->getValue()}`; near: " . $near; } else { $near = substr($this->stream->getSource(), 0, strlen($this->stream->getSource())); $message = "Ternary else expected but end of stream reached; near: " . $near; } throw new SyntaxErrorException($message); }); $this->stream->next(); $else = $this->parseExpression($subPrecedence); // Create the ternary operator node $node = $operatorNode($node, $if, $else); } return $node; }
/** * Test if the `getTernaryOperator` method throws an exception if the requested operator doesn't exists. * * @expectedException \com\mohiva\pyramid\exceptions\UnsupportedOperatorException */ public function testGetTernaryOperatorThrowsException() { $token = new Token(1, '?', 1); $table = new OperatorTable(); $table->getTernaryOperator($token); }