Browse Source

Missing templates should raise exceptions.

Missing templates are a signal that a developer has made a mistake.
We should help them find this error and an exception is the simplest way
to signal an error to the developer.

Refs #8554
Mark Story 10 years ago
parent
commit
71c5e98139
2 changed files with 18 additions and 7 deletions
  1. 2 4
      src/View/StringTemplate.php
  2. 16 3
      tests/TestCase/View/StringTemplateTest.php

+ 2 - 4
src/View/StringTemplate.php

@@ -16,6 +16,7 @@ namespace Cake\View;
 
 use Cake\Core\Configure\Engine\PhpConfig;
 use Cake\Core\InstanceConfigTrait;
+use RuntimeException;
 
 /**
  * Provides an interface for registering and inserting
@@ -224,12 +225,9 @@ class StringTemplate
     public function format($name, array $data)
     {
         if (!isset($this->_compiled[$name])) {
-            return null;
+            throw new RuntimeException("Cannot find template named '$name'.");
         }
         list($template, $placeholders) = $this->_compiled[$name];
-        if ($template === null) {
-            return null;
-        }
 
         if (isset($data['templateVars'])) {
             $data += $data['templateVars'];

+ 16 - 3
tests/TestCase/View/StringTemplateTest.php

@@ -95,9 +95,6 @@ class StringTemplateTest extends TestCase
         ];
         $this->template->add($templates);
 
-        $result = $this->template->format('not there', []);
-        $this->assertNull($result);
-
         $result = $this->template->format('text', ['text' => '']);
         $this->assertSame('', $result);
 
@@ -143,6 +140,22 @@ class StringTemplateTest extends TestCase
     }
 
     /**
+     * Test formatting a missing template.
+     *
+     * @expectedException RuntimeException
+     * @expectedExceptionMessage Cannot find template named 'missing'
+     * @return void
+     */
+    public function testFormatMissingTemplate()
+    {
+        $templates = [
+            'text' => '{{text}}',
+        ];
+        $this->template->add($templates);
+        $this->template->format('missing', ['text' => 'missing']);
+    }
+
+    /**
      * Test loading templates files in the app.
      *
      * @return void