Skip to content

Reader

Type reader component

The reader turns the native type of a reflected constant, property, function or parameter into the same AST the parser builds.

composer require type-lang/reader

Requirements:

  • PHP >= 8.1

Every method of TypeLang\Reader\ReflectionReader takes a Reflection object and returns a TypeNode, or null when no type is declared. The results below are shown as the pretty printer prints them.

final class Example
{
public const int MAX = 100;
public ?DateTimeInterface $bannedAt;
public $untyped;
public function find(Countable $items): Generator|false { /* ... */ }
}
$reader = new TypeLang\Reader\ReflectionReader();
$reader->findConstantType(new ReflectionClassConstant(Example::class, 'MAX'));
// int
$reader->findPropertyType(new ReflectionProperty(Example::class, 'bannedAt'));
// ?\DateTimeInterface
$reader->findPropertyType(new ReflectionProperty(Example::class, 'untyped'));
// null
$method = new ReflectionMethod(Example::class, 'find');
$reader->findFunctionType($method);
// \Generator|false
$reader->findParameterType($method->getParameters()[0]);
// \Countable

getType() converts a ReflectionType you already hold:

$reader->getType($method->getReturnType());
// \Generator|false
PHP AST
Example \Example: a class name is fully qualified
int, static, mixed as written
?Foo, Foo|null ?\Foo: a NullableTypeNode
A|B a UnionTypeNode
A&B an IntersectionTypeNode
no type null, not mixed

Since PHP 8.4 a set hook may take another type than the property gives. The second argument of findPropertyType() selects the side:

final class Post
{
public string $slug {
set(string|Stringable $value) {
$this->slug = (string) $value;
}
}
}
$property = new ReflectionProperty(Post::class, 'slug');
$reader->findPropertyType($property);
// string

A property without a typed set hook gives its read type for both.

A ReflectionType of an unknown kind throws an Unrecognized{Constant|Property|Function|Parameter}TypeException naming the element. Every exception of the reader implements TypeLang\Reader\Exception\ReaderExceptionInterface.