From 1a18d1c5bad164cb0d2e4584578a76273af7feaf Mon Sep 17 00:00:00 2001 From: Brad Mostert Date: Sat, 13 Oct 2018 13:36:28 +0200 Subject: [PATCH] Add Support for CASE ... END AS alias --- src/Components/CaseExpression.php | 69 +++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/src/Components/CaseExpression.php b/src/Components/CaseExpression.php index 820947bfb..a256f8996 100644 --- a/src/Components/CaseExpression.php +++ b/src/Components/CaseExpression.php @@ -7,6 +7,7 @@ namespace PhpMyAdmin\SqlParser\Components; use PhpMyAdmin\SqlParser\Component; +use PhpMyAdmin\SqlParser\Context; use PhpMyAdmin\SqlParser\Parser; use PhpMyAdmin\SqlParser\Token; use PhpMyAdmin\SqlParser\TokensList; @@ -55,6 +56,13 @@ class CaseExpression extends Component */ public $else_result; + /** + * The alias of this CASE statement + * + * @var string + */ + public $alias; + /** * The sub-expression. * @@ -94,6 +102,13 @@ public static function parse(Parser $parser, TokensList $list, array $options = */ $type = 0; + /** + * Whether an alias is expected + * + * @bool + */ + $alias = false; + ++$list->idx; // Skip 'CASE' for (; $list->idx < $list->count; ++$list->idx) { @@ -201,6 +216,56 @@ public static function parse(Parser $parser, TokensList $list, array $options = $list->tokens[$list->idx - 1] ); } else { + + // Parse alias for CASE statement + for (; $list->idx < $list->count; ++$list->idx) { + $token = $list->tokens[$list->idx]; + + // Skipping whitespaces and comments. + if (($token->type === Token::TYPE_WHITESPACE) + || ($token->type === Token::TYPE_COMMENT) + ) { + continue; + } + + // + if($token->type === Token::TYPE_KEYWORD + && $token->keyword === 'AS'){ + + if ($alias) { + $parser->error( + 'An alias was expected.', + $token + ); + break; + } + $alias = true; + continue; + } + + if ($alias){ + + // An alias is expected (the keyword `AS` was previously found). + if (!empty($ret->alias)) { + $parser->error('An alias was previously found.', $token); + break; + } + $ret->alias = $token->value; + $alias = false; + + continue; + } + + break; + } + if ($alias) { + $parser->error( + 'An alias was expected.', + $list->tokens[$list->idx - 1] + ); + } + + $ret->expr = self::build($ret); } @@ -241,6 +306,10 @@ public static function build($component, array $options = array()) } $ret .= 'END'; + if ($component->alias) { + $ret .= ' AS ' . Context::escape($component->alias); + } + return $ret; } }