Skip to content

Commit 57debbf

Browse files
author
Jeroen Versteeg
committed
Objects with __toString magic method are valid string-typed values
``` {% set foo %}Hello{% endset %} {% types {foo: 'string'} %} ``` Actually, `$context['foo'] instanceof Twig\Markup`.
1 parent 303e066 commit 57debbf

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"name": "Jeroen Versteeg"
99
}
1010
],
11-
"version": "1.0.7",
11+
"version": "1.0.8",
1212
"autoload": {
1313
"psr-4": {
1414
"AlisQI\\TwigQI\\": "src/"

src/Assertion/AssertType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public static function matches($value, string $type): bool
2727
}
2828

2929
return match ($type) {
30-
'string' => is_string($value),
30+
'string' => is_string($value) || (is_object($value) && method_exists($value, '__toString')),
3131
'number' => is_int($value) || is_float($value),
3232
'boolean' => is_bool($value),
3333
'iterable' => is_iterable($value),

tests/TypeAssertionsTest.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
namespace AlisQI\TwigQI\Tests;
66

77
use ArrayIterator;
8+
use DateTime;
89
use Exception;
10+
use Twig\Markup;
911
use Twig\Node\Node;
1012

1113
class TypeAssertionsTest extends AbstractTestCase
@@ -74,11 +76,13 @@ public static function getTypes(): array
7476
['string', 'hello', true],
7577
['string', '', true],
7678
['string', '0', true],
79+
['string', new Markup('hello', 'UTF-8'), true], // class Markup implements \Stringable
80+
['string', new Exception(), true], // Exception has __toString()
7781

7882
['string', true, false],
7983
['string', 1, false],
8084
['string', [], false],
81-
['string', new Exception(), false],
85+
['string', new DateTime(), false],
8286

8387
['number', 0, true],
8488
['number', 1, true],

0 commit comments

Comments
 (0)