Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Allow null coalesce operator in evaluation (#522) #572

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
namespace TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression;

/*
* This file belongs to the package "TYPO3 Fluid".
* See LICENSE.txt that was shipped with this package.
*/

use TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler;
use TYPO3Fluid\Fluid\Core\Parser\BooleanParser;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\BooleanNode;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\Variables\VariableExtractor;

/**
* Ternary Condition Node - allows the shorthand version
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CDRO, the comments in this file still refer to the ternary operator...

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing this out, I've corrected this now.

* of a condition to be written as `{var ? thenvar : elsevar}`
*/
class NullcoalescingExpressionNode extends AbstractExpressionNode
{

/**
* Pattern which detects ternary conditions written in shorthand
* syntax, e.g. {checkvar ? thenvar : elsevar}.
*/
public static $detectionExpression = '/
(
{ # Start of shorthand syntax
(?: # Math expression is composed of...
[\\!_a-zA-Z0-9.\(\)\!\|\&\\\'\'\"\=\<\>\%\s\{\}\:\,]+ # Check variable side
[\s]?\?\?[\s]?
[_a-zA-Z0-9.\s\'\"\\.]+ # Fallback value side
)
} # End of shorthand syntax
)/x';

/**
* Filter out variable names form expression
*/
protected static $variableDetection = '/[^\'_a-zA-Z0-9\.\\\\]{0,1}([_a-zA-Z0-9\.\\\\]*)[^\']{0,1}/';

/**
* @param RenderingContextInterface $renderingContext
* @param string $expression
* @param array $matches
* @return mixed
*/
public static function evaluateExpression(RenderingContextInterface $renderingContext, $expression, array $matches)
{
$parts = preg_split('/([\?\?])/s', $expression);
$parts = array_map([__CLASS__, 'trimPart'], $parts);

foreach($parts as $part) {
$value = static::getTemplateVariableOrValueItself($part, $renderingContext);
if(!is_null($value)) {
return $value;
}
}

return null;
}


/**
* @param mixed $candidate
* @param RenderingContextInterface $renderingContext
* @return mixed
*/
protected static function getTemplateVariableOrValueItself($candidate, RenderingContextInterface $renderingContext)
{
$variables = $renderingContext->getVariableProvider()->getAll();
$extractor = new VariableExtractor();
$suspect = $extractor->getByPath($variables, $candidate);

if (is_numeric($candidate)) {
$suspect = $candidate;
} elseif (mb_strpos($candidate, '\'') === 0) {
$suspect = trim($candidate, '\'');
} elseif (mb_strpos($candidate, '"') === 0) {
$suspect = trim($candidate, '"');
}

return $suspect;
}
}
2 changes: 2 additions & 0 deletions src/Core/Rendering/RenderingContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use TYPO3Fluid\Fluid\Core\Parser\Interceptor\Escape;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\CastingExpressionNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\MathExpressionNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\NullcoalescingExpressionNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\TernaryExpressionNode;
use TYPO3Fluid\Fluid\Core\Parser\TemplateParser;
use TYPO3Fluid\Fluid\Core\Parser\TemplateProcessor\EscapingModifierTemplateProcessor;
Expand Down Expand Up @@ -106,6 +107,7 @@ class RenderingContext implements RenderingContextInterface
protected $expressionNodeTypes = [
CastingExpressionNode::class,
MathExpressionNode::class,
NullcoalescingExpressionNode::class,
TernaryExpressionNode::class,
];

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
namespace TYPO3Fluid\Fluid\Tests\Unit\Core\Parser\SyntaxTree;

/*
* This file belongs to the package "TYPO3 Fluid".
* See LICENSE.txt that was shipped with this package.
*/

use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\Expression\NullcoalescingExpressionNode;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContext;
use TYPO3Fluid\Fluid\Core\Variables\StandardVariableProvider;
use TYPO3Fluid\Fluid\Tests\UnitTestCase;

/**
* Class TernaryExpressionNodeTest
*/
class NullcoalescingExpressionNodeTest extends UnitTestCase
{


/**
* @dataProvider getEvaluateExpressionTestValues
* @param string $expression
* @param array $variables
* @param mixed $expected
*/
public function testEvaluateExpression($expression, array $variables, $expected)
{
$renderingContext = new RenderingContext();
$renderingContext->setVariableProvider(new StandardVariableProvider($variables));
$result = NullcoalescingExpressionNode::evaluateExpression($renderingContext, $expression, []);
$this->assertEquals($expected, $result);
}

/**
* @return array
*/
public function getEvaluateExpressionTestValues()
{
return [
['{a ?? 1}', ['a' => 'a'], 'a'],
['{a ?? 1}', ['a' => null], 1],
['{a ?? b}', ['a' => 'a', 'b' => 'b'], 'a'],
['{a ?? b}', ['a' => null, 'b' => 'b'], 'b'],
['{a ?? b ?? c}', ['a' => 1, 'b' => 2, 'c' => 3], 1],
['{a ?? b ?? c}', ['a' => 1, 'b' => null, 'c' => 3], 1],
['{a ?? b ?? c}', ['a' => null, 'b' => 2, 'c' => 3], 2],
['{a ?? b ?? c}', ['a' => null, 'b' => null, 'c' => 3], 3],
['{a ?? b ?? c}', ['a' => 'd', 'b' => 'e', 'c' => 'f'], 'd'],
['{a ?? b ?? c}', ['a' => 'd', 'b' => null, 'c' => 'f'], 'd'],
['{a ?? b ?? c}', ['a' => null, 'b' => 'e', 'c' => 'f'], 'e'],
['{a ?? b ?? c}', ['a' => null, 'b' => null, 'c' => 'f'], 'f'],
Comment on lines +49 to +52
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These 4 cases can be dropped since they are basically the same as the 4 before them, only a bit more confusing. ;-)

Copy link
Author

@CDRO CDRO Oct 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, absolutely, but I guess I'll leave them, because in the beginning, $a was always equals to a which ended in some false positives that I tried to avoid with this test, but yeah, makes sense to remove them, although assuming that '1' is interpreted as string instead of an integer might be a bit of a strech. I'll have to test it :-)

['{a ?? b ?? c}', ['a' => null, 'b' => null, 'c' => null], null],
['{a ?? b ?? \'test\'}', ['a' => null, 'b' => null], 'test'],
['{a ?? b ?? "test"}', ['a' => null, 'b' => null], 'test'],

];
}
}