1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-22 05:41:20 +01:00

Fix #4798 - improve conversion from type back to PhpParser node

This commit is contained in:
Matt Brown 2020-12-07 14:39:58 -05:00
parent f5dd6e76f8
commit 8a76a43d8c
2 changed files with 40 additions and 21 deletions

View File

@ -342,6 +342,27 @@ class StubsGenerator
if ($atomic_type instanceof Type\Atomic\TArray) {
return new PhpParser\Node\Expr\Array_([]);
}
if ($atomic_type instanceof Type\Atomic\TKeyedArray) {
$new_items = [];
foreach ($atomic_type->properties as $property_name => $property_type) {
if ($atomic_type->is_list) {
$key_type = null;
} elseif (\is_int($property_name)) {
$key_type = new PhpParser\Node\Scalar\LNumber($property_name);
} else {
$key_type = new PhpParser\Node\Scalar\String_($property_name);
}
$new_items[] = new PhpParser\Node\Expr\ArrayItem(
self::getExpressionFromType($property_type),
$key_type
);
}
return new PhpParser\Node\Expr\Array_($new_items);
}
}
return new PhpParser\Node\Scalar\String_('Psalm could not infer this type');

View File

@ -102,6 +102,25 @@ class AttributeTest extends TestCase
[],
'8.0'
],
'convertKeyedArray' => [
'<?php
#[Attribute(Attribute::TARGET_CLASS)]
class Route {
private $methods = [];
/**
* @param string[] $methods
*/
public function __construct(array $methods = []) {
$this->methods = $methods;
}
}
#[Route(methods: ["GET"])]
class HealthController
{}',
[],
[],
'8.0'
],
];
}
@ -203,27 +222,6 @@ class AttributeTest extends TestCase
false,
'8.0'
],
'testReflectingClass74' => [
'<?php
abstract class BaseAttribute {
public function __construct(public string $name) {}
}
#[Attribute(Attribute::TARGET_CLASS)]
class Table extends BaseAttribute {}
/** @param class-string $s */
function foo(string $s) : void {
foreach ((new ReflectionClass($s))->getAttributes(BaseAttribute::class, 2) as $attr) {
$attribute = $attr->newInstance();
echo $attribute->name;
}
}',
'error_message' => 'UndefinedMethod',
[],
false,
'7.4'
],
'interfaceCannotBeAttributeClass' => [
'<?php
#[Attribute]