Browse Source

Format array data without errors.

If an array ends up in a string template, we should attempt to format
the data gracefully instead of triggering an error. Imploding on ''
seemed like the safest option at hand.

This is necessary to fix issues like #7361
Mark Story 10 years ago
parent
commit
0049cf633c
2 changed files with 30 additions and 1 deletions
  1. 5 1
      src/View/StringTemplate.php
  2. 25 0
      tests/TestCase/View/StringTemplateTest.php

+ 5 - 1
src/View/StringTemplate.php

@@ -233,7 +233,11 @@ class StringTemplate
         }
         }
         $replace = [];
         $replace = [];
         foreach ($placeholders as $placeholder) {
         foreach ($placeholders as $placeholder) {
-            $replace[] = isset($data[$placeholder]) ? $data[$placeholder] : null;
+            $replacement = isset($data[$placeholder]) ? $data[$placeholder] : null;
+            if (is_array($replacement)) {
+                $replacement = implode('', $replacement);
+            }
+            $replace[] = $replacement;
         }
         }
         return vsprintf($template, $replace);
         return vsprintf($template, $replace);
     }
     }

+ 25 - 0
tests/TestCase/View/StringTemplateTest.php

@@ -104,6 +104,31 @@ class StringTemplateTest extends TestCase
     }
     }
 
 
     /**
     /**
+     * Formatting array data should not trigger errors.
+     *
+     * @return void
+     */
+    public function testFormatArrayData()
+    {
+        $templates = [
+            'link' => '<a href="{{url}}">{{text}}</a>'
+        ];
+        $this->template->add($templates);
+
+        $result = $this->template->format('link', [
+            'url' => '/',
+            'text' => ['example', 'text']
+        ]);
+        $this->assertEquals('<a href="/">exampletext</a>', $result);
+
+        $result = $this->template->format('link', [
+            'url' => '/',
+            'text' => ['key' => 'example', 'text']
+        ]);
+        $this->assertEquals('<a href="/">exampletext</a>', $result);
+    }
+
+    /**
      * Test loading templates files in the app.
      * Test loading templates files in the app.
      *
      *
      * @return void
      * @return void