From 6485b4f5a1ef6a22084a0788c63f71c8a63d2c46 Mon Sep 17 00:00:00 2001 From: Adam Pippin Date: Mon, 15 Feb 2021 11:38:28 -0800 Subject: [PATCH] Add !expr function to allow inserting the result of evaluating an expression --- app/Engine/Cfnpp/Functions.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/app/Engine/Cfnpp/Functions.php b/app/Engine/Cfnpp/Functions.php index 51672d9..bf9395c 100644 --- a/app/Engine/Cfnpp/Functions.php +++ b/app/Engine/Cfnpp/Functions.php @@ -141,6 +141,11 @@ class Functions $expression = $parser->parse($condition->getValue()); $result = $expression->evaluate($this->options->getVariables()); + if (is_array($result)) + { + throw new \Exception('!if expression must evaluate down to a single value: '.$condition->getValue()); + } + if ($result) { $if_true->setName($node->hasName() ? $node->getName() : null); @@ -153,4 +158,28 @@ class Functions } return $if_false; } + + /** + * Calculate an expression. + * + * @param Node $node + * @param NodeFunction $function + * @return ?Node + */ + public function f_expr(Node $node, NodeFunction $function): ?Node + { + if (!($function instanceof NodeFunctionValue)) + { + throw new \Exception('!if requires scalar argument'); + } + + $parser = new \App\Engine\Cfnpp\Expression\Parser(); + $expression = $parser->parse($function->getValue()); + $result = $expression->evaluate($this->options->getVariables()); + + $result = Node::fromPhp($result); + $result->setName($node->hasName() ? $node->getName() : null); + + return $result; + } }