diff --git a/src/Runtime.php b/src/Runtime.php index f143ae9..736dd71 100644 --- a/src/Runtime.php +++ b/src/Runtime.php @@ -37,14 +37,19 @@ public static function lo(array $v): string /** * For {{#if}} and {{#unless}}. * - * @param array|string|int>|string|int|float|bool|null $v value to be tested + * @param array|string|int>|string|\Stringable|int|float|bool|null $v value to be tested * @param bool $zero include zero as true * * @return bool Return true when the value is not null nor false. */ - public static function ifvar(mixed $v, bool $zero): bool + public static function ifvar(mixed $v, bool $zero = false): bool { - return $v !== null && $v !== false && ($zero || ($v !== 0 && $v !== 0.0)) && $v !== '' && (!is_array($v) || count($v) > 0); + return $v !== null + && $v !== false + && ($zero || ($v !== 0 && $v !== 0.0)) + && $v !== '' + && (!$v instanceof \Stringable || (string) $v !== '') + && (!is_array($v) || count($v) > 0); } /** diff --git a/tests/RuntimeTest.php b/tests/RuntimeTest.php index 109857f..c696624 100644 --- a/tests/RuntimeTest.php +++ b/tests/RuntimeTest.php @@ -10,17 +10,19 @@ class RuntimeTest extends TestCase { public function testIfVar(): void { - $this->assertFalse(Runtime::ifvar(null, false)); - $this->assertFalse(Runtime::ifvar(0, false)); + $this->assertFalse(Runtime::ifvar(null)); + $this->assertFalse(Runtime::ifvar(0)); $this->assertTrue(Runtime::ifvar(0, true)); - $this->assertFalse(Runtime::ifvar(false, false)); - $this->assertTrue(Runtime::ifvar(true, false)); - $this->assertTrue(Runtime::ifvar(1, false)); - $this->assertFalse(Runtime::ifvar('', false)); - $this->assertTrue(Runtime::ifvar('0', false)); - $this->assertFalse(Runtime::ifvar([], false)); - $this->assertTrue(Runtime::ifvar([''], false)); - $this->assertTrue(Runtime::ifvar([0], false)); + $this->assertFalse(Runtime::ifvar(false)); + $this->assertTrue(Runtime::ifvar(true)); + $this->assertTrue(Runtime::ifvar(1)); + $this->assertFalse(Runtime::ifvar('')); + $this->assertTrue(Runtime::ifvar('0')); + $this->assertFalse(Runtime::ifvar([])); + $this->assertTrue(Runtime::ifvar([''])); + $this->assertTrue(Runtime::ifvar([0])); + $this->assertFalse(Runtime::ifvar(self::createStringable(''))); + $this->assertTrue(Runtime::ifvar(self::createStringable('0'))); } public function testIsec(): void @@ -41,4 +43,16 @@ public function testWi(): void $this->assertSame('{"a":"b"}', Runtime::wi($cx, ['a' => 'b'], null, ['a' => 'c'], function ($c, $i) {return json_encode($i); })); $this->assertSame('-b=', Runtime::wi($cx, 'b', null, ['a' => 'b'], function ($c, $i) {return "-$i="; })); } + + private static function createStringable(string $value): \Stringable + { + return new class ($value) implements \Stringable { + public function __construct(private string $value) {} + + public function __toString(): string + { + return $this->value; + } + }; + } }