Browse Source

Make h() not puke when objects are passed in.

This can happen in the default Exception rendering,
if an object is in the viewVars.
mark_story 14 years ago
parent
commit
adf52235d0
2 changed files with 18 additions and 1 deletions
  1. 9 0
      lib/Cake/Test/Case/BasicsTest.php
  2. 9 1
      lib/Cake/basics.php

+ 9 - 0
lib/Cake/Test/Case/BasicsTest.php

@@ -19,6 +19,7 @@
 
 require_once CAKE . 'basics.php';
 App::uses('Folder', 'Utility');
+App::uses('CakeResponse', 'Network');
 
 /**
  * BasicsTest class
@@ -234,6 +235,14 @@ class BasicsTest extends CakeTestCase {
 			'n' => ' '
 		);
 		$this->assertEqual($expected, $result);
+
+		$obj = new stdClass();
+		$result = h($obj);
+		$this->assertEquals('(object)stdClass', $result);
+
+		$obj = new CakeResponse(array('body' => 'Body content'));
+		$result = h($obj);
+		$this->assertEquals('Body content', $result);
 	}
 
 /**

+ 9 - 1
lib/Cake/basics.php

@@ -148,7 +148,9 @@ if (!function_exists('sortByKey')) {
 /**
  * Convenience method for htmlspecialchars.
  *
- * @param string $text Text to wrap through htmlspecialchars
+ * @param mixed $text Text to wrap through htmlspecialchars.  Also works with arrays, and objects.
+ *    Arrays will be mapped and have all their elements escaped.  Objects will be string cast if they
+ *    implement a `__toString` method.  Otherwise the class name will be used.
  * @param boolean $double Encode existing html entities
  * @param string $charset Character set to use when escaping.  Defaults to config value in 'App.encoding' or 'UTF-8'
  * @return string Wrapped text
@@ -161,6 +163,12 @@ function h($text, $double = true, $charset = null) {
 			$texts[$k] = h($t, $double, $charset);
 		}
 		return $texts;
+	} elseif (is_object($text)) {
+		if (method_exists($text, '__toString')) {
+			$text = (string) $text;
+		} else {
+			$text = '(object)' . get_class($text);
+		}
 	}
 
 	static $defaultCharset = false;