Skip to content

fix: Fix scoping of new statement with the new parent not being a name #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 19, 2025
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
86 changes: 86 additions & 0 deletions specs/string-literal/new.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,90 @@ class Ya_1

PHP,
),

'new parent is a class name' => <<<'PHP'
<?php
namespace Acme;

class BplaaYai {}

new BplaaYai('abc');

----
<?php

namespace Humbug\Acme;

class BplaaYai
{
}
new BplaaYai('abc');

PHP,

'new parent is a variable' => <<<'PHP'
<?php
namespace Acme;

class BplaaYai {}

$class = '\Acme\BplaaYai';
new $class('abc');

----
<?php

namespace Humbug\Acme;

class BplaaYai
{
}
$class = 'Humbug\Acme\BplaaYai';
new $class('abc');

PHP,

'new parent is an expression (variable)' => <<<'PHP'
<?php
namespace Acme;

class BplaaYai {}

$class = '\Acme\BplaaYai';
new $class('abc');

----
<?php

namespace Humbug\Acme;

class BplaaYai
{
}
$class = 'Humbug\Acme\BplaaYai';
new $class('abc');

PHP,

'new parent is an anonymous class' => <<<'PHP'
<?php
namespace Acme;

class BplaaYai {}

new class('abc') {};

----
<?php

namespace Humbug\Acme;

class BplaaYai
{
}
new class('abc')
{
};

PHP,
];
9 changes: 4 additions & 5 deletions src/PhpParser/NodeVisitor/StringScalarPrefixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,10 @@ private function prefixNewStringArg(String_ $string, New_ $newNode): String_
{
$class = $newNode->class;

if (!($class instanceof Name)) {
throw UnexpectedParsingScenario::create();
}

if (in_array(strtolower($class->toString()), self::DATETIME_CLASSES, true)) {
if ($class instanceof Name
&& in_array(strtolower($class->toString()), self::DATETIME_CLASSES, true)
) {
// Value cannot be a class name, hence we should not try to prefix it.
return $string;
}

Expand Down