Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/CurlyBraceOffsetRejector.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,18 @@ private static function closingParenOpensControlBlock(array $tokens, int $closeP
return true;
}

// `new class(...)` anonymous class ctor args — `{` opens class body, not offset access (#6881).
// `new class(...)` / `new readonly class(...)` anonymous class ctor args — `{` opens class body (#6881, #17467).
if (T_CLASS === $beforeOpen[0]) {
$beforeClass = self::previousSignificantToken($tokens, $openParenIndex - 2);
if (\is_array($beforeClass) && T_NEW === $beforeClass[0]) {
return true;
}
if (\is_array($beforeClass) && \defined('T_READONLY') && T_READONLY === $beforeClass[0]) {
$beforeReadonly = self::previousSignificantToken($tokens, $openParenIndex - 4);
if (\is_array($beforeReadonly) && T_NEW === $beforeReadonly[0]) {
return true;
}
}
}

if (T_STRING === $beforeOpen[0]) {
Expand Down
21 changes: 21 additions & 0 deletions test/compliance/cases/language/readonly_anonymous_ctor_args.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
--TEST--
Language: new readonly class(...) constructor args (issue #17467, Zend/zend_compile.c)
--SKIPIF--
<?php
if (!class_exists('PHPCompiler\\CompilerVersion')) {
require __DIR__ . '/../../../../vendor/autoload.php';
}
if (!PHPCompiler\CompilerVersion::supportsReadonlyAnonymousClass()) {
die('skip new readonly class requires PHP 8.3+ forward profile');
}
?>
--FILE--
<?php
declare(strict_types=1);

$o = new readonly class(5) {
public function __construct(public int $x) {}
};
echo $o->x, "\n";
--EXPECT--
5
9 changes: 9 additions & 0 deletions test/repro/maintainer_gap_readonly_anonymous_ctor_args.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

$o = new readonly class(5) {
public function __construct(public int $x) {}
};

echo $o->x, "\n";
6 changes: 6 additions & 0 deletions test/unit/CurlyBraceOffsetRejectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,10 @@ public function testAnonymousClassCtorArgsBraceIsAllowed(): void
$code = '<?php $o = new class(1) { public function __construct(private int $x) {} };';
self::assertSame($code, CurlyBraceOffsetRejector::reject($code, 'test.php'));
}

public function testReadonlyAnonymousClassCtorArgsBraceIsAllowed(): void
{
$code = '<?php $o = new readonly class(5) { public function __construct(public int $x) {} };';
self::assertSame($code, CurlyBraceOffsetRejector::reject($code, 'test.php'));
}
}