diff --git a/core/lib/Drupal/Component/Utility/Twig.php b/core/lib/Drupal/Component/Utility/Twig.php new file mode 100644 index 0000000..42fb23d --- /dev/null +++ b/core/lib/Drupal/Component/Utility/Twig.php @@ -0,0 +1,44 @@ + $replacement); foreach(array_reverse($parts) as $key) { - assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/\', $key) === 1', 'Tokens need to be valid Twig variables.'); + Twig::assertValidVariable($key); $token_array = array($key => $token_array); } $twig_tokens[$top] = $token_array; diff --git a/core/modules/views/src/Tests/Plugin/PluginBaseTest.php b/core/modules/views/src/Tests/Plugin/PluginBaseTest.php index 0ef1724..cf9534c 100644 --- a/core/modules/views/src/Tests/Plugin/PluginBaseTest.php +++ b/core/modules/views/src/Tests/Plugin/PluginBaseTest.php @@ -44,13 +44,60 @@ public function testViewsTokenReplace() { } /** + * Tests that array tokens are replaced correctly. + */ + public function testViewsTokenArrayReplace() { + $text = '{{ foo.bar.baz }}'; + $tokens = ['foo' => ['bar' => ['baz' => 'I am replaced.']]]; + + $result = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($text, $tokens) { + return $this->testPluginBase->viewsTokenReplace($text, $tokens); + }); + $this->assertIdentical($result, 'I am replaced.'); + + // Array tokens can also be passed using dot-notation. + $tokens = ['foo.bar.baz' => 'I am replaced.']; + $result = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($text, $tokens) { + return $this->testPluginBase->viewsTokenReplace($text, $tokens); + }); + $this->assertIdentical($result, 'I am replaced.'); + } + + /** * Tests viewsTokenReplace without any twig tokens. */ - public function testViewsTokenReplaceWithTwigTokens() { + public function testViewsTokenReplaceWithoutTwigTokens() { $text = 'Just some text'; $tokens = []; $result = $this->testPluginBase->viewsTokenReplace($text, $tokens); - $this->assertIdentical($result, 'Just some text'); + $this->assertIdentical($result, $text); + + $text = 'Just {{ some }} text with brackets and no tokens'; + $tokens = []; + $result = $this->testPluginBase->viewsTokenReplace($text, $tokens); + $this->assertIdentical($result, $text); + } + + /** + * Test that invalid tokens are flagged appropriately. + */ + public function testViewsInvalidTokens() { + // We cannot use @expectedException since this class does not extend from + // PHPUnit_Framework_TestCase. + try { + $text = '{{ foo-bar }}'; + $tokens = [ + '{{ foo-bar }}' => 'bogus', + ]; + + \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($text, $tokens) { + return $this->testPluginBase->viewsTokenReplace($text, $tokens); + }); + $this->fail('Failed to assert that "foo-bar" is an illegal Twig variable.'); + } + catch(\Exception $e) { + $this->assertIdentical('"foo-bar" is not a valid Twig variable.', $e->getMessage()); + } } }