Skip to content

Commit 931053b

Browse files
committed
Fix strict handling of length on objects
1 parent f8675b5 commit 931053b

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

src/Runtime.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,16 +164,16 @@ public static function prop(mixed $base, string $key): mixed
164164

165165
/**
166166
* Terminal .length lookup: returns count() for arrays (since PHP arrays have no native .length
167-
* property), an explicit 'length' key if present, or null for non-array bases.
168-
* When $strict is true, throws for any non-array base, mirroring HBS.js strict-mode behavior.
167+
* property), an explicit 'length' key if present, or null for non-array/non-object bases.
168+
* When $strict is true, throws for objects without a 'length' property and for all scalar/null bases.
169169
*/
170170
public static function lookupLength(mixed $base, bool $strict = false): mixed
171171
{
172172
if (is_array($base)) {
173173
return array_key_exists('length', $base) ? $base['length'] : count($base);
174174
}
175-
if (is_object($base)) {
176-
return $base->length ?? null;
175+
if (is_object($base) && property_exists($base, 'length')) {
176+
return $base->length;
177177
}
178178
if ($strict) {
179179
$desc = match (true) {

tests/ErrorTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ public static function renderErrorProvider(): array
9595
'data' => ['foo' => 42],
9696
'expected' => '"length" not defined in 42',
9797
],
98+
'strict mode .length on object without length property' => [
99+
'template' => '{{foo.length}}',
100+
'options' => new Options(strict: true),
101+
'data' => ['foo' => (object) ['name' => 'test']],
102+
'expected' => '"length" not defined in stdClass',
103+
],
98104
'strict mode null property access in if' => [
99105
'template' => '{{#if foo.bar}}bad{{else}}OK{{/if}}',
100106
'options' => new Options(strict: true),

0 commit comments

Comments
 (0)