Explorar o código

[WebBundle] Fixed issue in Mustache when a value is not provided for a token.

Kris Wallsmith %!s(int64=15) %!d(string=hai) anos
pai
achega
c6f21e44a3

+ 8 - 3
src/Symfony/Framework/WebBundle/Util/Mustache.php

@@ -20,14 +20,19 @@ namespace Symfony\Framework\WebBundle\Util;
  */
 class Mustache
 {
-  static public function renderFile($file, $parameters)
+  static public function renderString($string, $parameters)
   {
     $replacer = function ($match) use($parameters)
     {
-      return isset($parameters[$match[1]]) ? $parameters[$match[1]] : "{{ $match[0] }}";
+      return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
     };
 
-    file_put_contents($file, preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, file_get_contents($file)));
+    return preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
+  }
+
+  static public function renderFile($file, $parameters)
+  {
+    file_put_contents($file, static::renderString(file_get_contents($file), $parameters));
   }
 
   static public function renderDir($dir, $parameters)

+ 25 - 0
tests/Symfony/Tests/Framework/WebBundle/Util/MustacheTest.php

@@ -0,0 +1,25 @@
+<?php
+
+/*
+ * This file is part of the symfony package.
+ *
+ * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Tests\Framework\WebBundle\Util;
+
+use Symfony\Framework\WebBundle\Util\Mustache;
+
+class MustacheTest extends \PHPUnit_Framework_TestCase
+{
+  public function testRenderString()
+  {
+    $template = 'Hi {{ you }}, my name is {{ me }}!';
+    $expected = 'Hi {{ you }}, my name is Kris!';
+
+    $this->assertEquals(Mustache::renderString($template, array('me' => 'Kris')), $expected, '::renderString() does not modify unknown parameters');
+  }
+}