diff --git a/app/Cfnpp/Functions.php b/app/Cfnpp/Functions.php index debea51..79eb493 100644 --- a/app/Cfnpp/Functions.php +++ b/app/Cfnpp/Functions.php @@ -16,6 +16,13 @@ use App\Dom\NodeFunctionValue; */ class Functions { + /** + * For now, generate incremental condition names. + * @todo + * @var int + */ + public static $condition_idx = 0; + /** * cfnpp compiler. * @var Compiler @@ -149,26 +156,42 @@ class Functions $if_true = $nodes[1]; $if_false = sizeof($nodes) == 3 ? $nodes[2] : null; - $parser = new \App\Cfnpp\Expression\Parser(); - $expression = $parser->parse($condition->getValue()); - $result = $expression->evaluate($this->options->getVariables()); + $expression = new \App\Cfnpp\Expression\Expression($condition->getValue(), $this->options); - if (is_array($result)) + // We need a single resulting node as a final value either as a scalar or + // if we want to convert to cloudformation. + if ($expression->count() > 1) { throw new \Exception('!if expression must evaluate down to a single value: '.$condition->getValue()); } - if ($result) + if ($expression->isComplete()) { - $if_true->setName($node->hasName() ? $node->getName() : null); - return $if_true; + // We know the final result, we can resolve this directly. + if ($expression->getValue()) + { + $if_true->setName($node->hasName() ? $node->getName() : null); + return $if_true; + } + elseif (isset($if_false)) + { + $if_false->setName($node->hasName() ? $node->getName() : null); + return $if_false; + } + return null; } - if (isset($if_false)) - { - $if_false->setName($node->hasName() ? $node->getName() : null); - } - return $if_false; + // Create condition + // Generate Cfn Fn::If + $condition_name = 'Condition'.(static::$condition_idx++); + $this->compiler->addCondition($condition_name, Node::fromPhp($expression->toCloudformation())); + + $n_orig = new Node(null, $node->hasName() ? $node->getName() : null); + $n_if = new Node($n_orig, 'Fn::If'); + $n_if->addChild(new NodeValue($n_if, null, $condition_name)); + $n_if->addChild($if_true); + $n_if->addChild($if_false); + return $n_if; } /** @@ -194,5 +217,4 @@ class Functions return $result; } - }