1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00

improve psalter capacities for anonymous class extending real classes (#5146)

This commit is contained in:
orklah 2021-02-04 15:59:38 +01:00 committed by GitHub
parent ff325b3e70
commit 343d020408
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 66 additions and 3 deletions

View File

@ -186,7 +186,8 @@ class NewAnalyzer extends \Psalm\Internal\Analyzer\Statements\Expression\CallAna
}
if ($stmt->class instanceof PhpParser\Node\Stmt\Class_) {
$result_atomic_type = new Type\Atomic\TAnonymousClassInstance($fq_class_name);
$extends = $stmt->class->extends ? (string) $stmt->class->extends : null;
$result_atomic_type = new Type\Atomic\TAnonymousClassInstance($fq_class_name, false, $extends);
} else {
$result_atomic_type = new TNamedObject($fq_class_name);
$result_atomic_type->was_static = $from_static;

View File

@ -6,6 +6,21 @@ namespace Psalm\Type\Atomic;
*/
class TAnonymousClassInstance extends TNamedObject
{
/**
* @var string|null
*/
public $extends;
/**
* @param string $value the name of the object
*/
public function __construct(string $value, bool $was_static = false, ?string $extends = null)
{
parent::__construct($value, $was_static);
$this->extends = $extends;
}
public function toPhpString(
?string $namespace,
array $aliased_classes,
@ -15,7 +30,7 @@ class TAnonymousClassInstance extends TNamedObject
): ?string {
return $php_major_version > 7
|| ($php_major_version === 7 && $php_minor_version >= 2)
? 'object' : null;
? ($this->extends ?? 'object') : null;
}
/**
@ -28,6 +43,6 @@ class TAnonymousClassInstance extends TNamedObject
?string $this_class,
bool $use_phpdoc_format
): string {
return 'object';
return $this->extends ?? 'object';
}
}

View File

@ -1012,6 +1012,53 @@ class MissingReturnTypeTest extends FileManipulationTestCase
false,
true,
],
'returnExtendedAnonymClass' => [
'<?php
class A {}
function f()
{
$a = new class extends A {};
/** @psalm-trace $a */;
return $a;
}',
'<?php
class A {}
function f(): A
{
$a = new class extends A {};
/** @psalm-trace $a */;
return $a;
}',
'8.0',
['MissingReturnType'],
false,
true,
],
'returnExtendedAnonymClassOld' => [
'<?php
class A {}
function f()
{
return new class extends A {};
}',
'<?php
class A {}
/**
* @return A
*/
function f()
{
return new class extends A {};
}',
'7.0',
['MissingReturnType'],
false,
true,
],
];
}
}