Skip to content

Commit

Permalink
Merge pull request #8723 from weirdan/allow-new-on-objects
Browse files Browse the repository at this point in the history
Fixes #8355
  • Loading branch information
weirdan committed Nov 19, 2022
2 parents 4e17585 + 6554aa0 commit 6d03c32
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
Expand Up @@ -849,7 +849,9 @@ private static function analyzeConstructorExpression(
)) {
// fall through
}
} elseif ($lhs_type_part instanceof TMixed) {
} elseif ($lhs_type_part instanceof TMixed
|| $lhs_type_part instanceof TObject
) {
IssueBuffer::maybeAdd(
new MixedMethodCall(
'Cannot call constructor on an unknown class',
Expand All @@ -865,6 +867,9 @@ private static function analyzeConstructorExpression(
&& $stmt_class_type->ignore_nullable_issues
) {
// do nothing
} elseif ($lhs_type_part instanceof TNamedObject) {
$new_type = Type::combineUnionTypes($new_type, new Union([$lhs_type_part]));
continue;
} elseif (IssueBuffer::accepts(
new UndefinedClass(
'Type ' . $lhs_type_part . ' cannot be called as a class',
Expand Down
58 changes: 57 additions & 1 deletion tests/ClassTest.php
Expand Up @@ -795,6 +795,53 @@ interface I extends Traversable {}
abstract class C implements I {}
',
],
'newOnNamedObject' => [
'code' => '<?php
$o = new stdClass;
$o2 = new $o;
',
'assertions' => [
'$o2===' => 'stdClass',
],
],
'newOnObjectOfAnonymousClass' => [
'code' => '<?php
function f(): object {
$o = new class {};
return new $o;
}
',
],
'newOnObjectOfAnonymousExtendingNamed' => [
'code' => '<?php
function f(): Exception {
$o = new class extends Exception {};
return new $o;
}
',
],
'newOnObjectOfAnonymousClassImplementingNamed' => [
'code' => '<?php
interface I {}
function f(): I {
$o = new class implements I {};
return new $o;
}
',
],
'throwAnonymousObjects' => [
'code' => '<?php
throw new class extends Exception {};
',
],
'throwTheResultOfNewOnAnAnonymousClass' => [
'code' => '<?php
declare(strict_types=1);
$test = new class extends \Exception { };
throw new $test();
'
]
];
}

Expand Down Expand Up @@ -1151,7 +1198,16 @@ class Foo
class Bar {}
',
'error_message' => 'ReservedWord',
]
],
'newOnObject' => [
'code' => '<?php
function f(object $o): object
{
return new $o;
}
',
'error_message' => 'MixedMethodCall',
],
];
}
}

0 comments on commit 6d03c32

Please sign in to comment.