diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php index 6a54e8e..b873f6c 100644 --- a/core/lib/Drupal/Core/Template/Attribute.php +++ b/core/lib/Drupal/Core/Template/Attribute.php @@ -99,11 +99,14 @@ protected function createAttributeValue($name, $value) { elseif (is_bool($value)) { $value = new AttributeBoolean($name, $value); } - elseif (!is_object($value)) { + // If $value is int, string, null or other pure type lets pass it directly. + // If $value is object but implements __toString() lets pass it + // and it will be typecasted to string later. + elseif (!is_object($value) || (is_object($value) && method_exists($value, '__toString'))) { $value = new AttributeString($name, $value); } // Provide a better exception message when invalid object is passed as value. - elseif (is_object($value) && !method_exists($value, '__toString')) { + elseif (is_object($value)) { throw new \Exception('"' . $name . '" attribute value of type "' . get_class($value) . '" can not be converted to string'); } diff --git a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php index 7ddb8bb..5eab437 100644 --- a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php +++ b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php @@ -275,6 +275,13 @@ public function createAttributeValuesProvider() { $result = new AttributeString($name, $value); $testCases[] = array($name, $value, $result); + + // Test object with render and __toString methods present + // but it is not instance of AttributeValueBase. + $value = $this->getMock('Drupal\Core\StringTranslation\TranslationWrapper', array(), array(), '', FALSE); + $result = new AttributeString($name, $value); + $testCases[] = array($name, $value, $result); + return $testCases; } @@ -303,11 +310,6 @@ public function createAttributeValueExceptionProvider() { $value = $this->getRandomGenerator()->object(); $testCases[] = array($name, $value); - // Test object with render and __toString methods present - // but it is not instance of AttributeValueBase. - $value = $this->getMock('Drupal\Core\StringTranslation\TranslationWrapper', array(), array(), '', FALSE); - $testCases[] = array($name, $value); - return $testCases; }