Use Stringable when possible

This commit is contained in:
Fabien Potencier
2024-08-26 17:09:29 +02:00
parent 303e3ea9d6
commit 11813da84d
6 changed files with 8 additions and 9 deletions
+1 -1
View File
@@ -142,7 +142,7 @@ class Error extends \Exception
}
if ($this->name) {
if (\is_string($this->name) || (\is_object($this->name) && method_exists($this->name, '__toString'))) {
if (\is_string($this->name) || $this->name instanceof \Stringable) {
$name = \sprintf('"%s"', $this->name);
} else {
$name = json_encode($this->name);
+2 -2
View File
@@ -1191,7 +1191,7 @@ final class CoreExtension extends AbstractExtension
return iterator_count($thing);
}
if (method_exists($thing, '__toString')) {
if ($thing instanceof \Stringable) {
return mb_strlen((string) $thing, $charset);
}
@@ -1328,7 +1328,7 @@ final class CoreExtension extends AbstractExtension
return !iterator_count($value);
}
if (\is_object($value) && method_exists($value, '__toString')) {
if ($value instanceof \Stringable) {
return '' === (string) $value;
}
+1 -1
View File
@@ -119,7 +119,7 @@ final class SandboxExtension extends AbstractExtension
public function ensureToStringAllowed($obj, int $lineno = -1, ?Source $source = null)
{
if ($this->isSandboxed($source) && \is_object($obj) && method_exists($obj, '__toString')) {
if ($this->isSandboxed($source) && $obj instanceof \Stringable) {
try {
$this->policy->checkMethodAllowed($obj, '__toString');
} catch (SecurityNotAllowedMethodError $e) {
+2 -3
View File
@@ -29,12 +29,11 @@ final class StringLoaderExtension extends AbstractExtension
*
* {{ include(template_from_string("Hello {{ name }}")) }}
*
* @param string $template A template as a string or object implementing __toString()
* @param string|null $name An optional name of the template to be used in error messages
* @param string|null $name An optional name of the template to be used in error messages
*
* @internal
*/
public static function templateFromString(Environment $env, $template, ?string $name = null): TemplateWrapper
public static function templateFromString(Environment $env, string|\Stringable $template, ?string $name = null): TemplateWrapper
{
return $env->createTemplate((string) $template, $name);
}
+1 -1
View File
@@ -16,7 +16,7 @@ namespace Twig;
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Markup implements \Countable, \JsonSerializable
class Markup implements \Countable, \JsonSerializable, \Stringable
{
private $content;
private $charset;
+1 -1
View File
@@ -93,7 +93,7 @@ final class EscaperRuntime implements RuntimeExtensionInterface
}
if (!\is_string($string)) {
if (\is_object($string) && method_exists($string, '__toString')) {
if ($string instanceof \Stringable) {
if ($autoescape) {
$c = \get_class($string);
if (!isset($this->safeClasses[$c])) {