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.
Installation
Section titled “Installation”composer require type-lang/readerRequirements:
PHP >= 8.1
Reading types
Section titled “Reading types”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]);// \CountablegetType() converts a ReflectionType you already hold:
$reader->getType($method->getReturnType());// \Generator|falseHow types are converted
Section titled “How types are converted”| 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 |
Read vs. Write
Section titled “Read vs. Write”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);// stringuse TypeLang\Reader\PropertyAccessDirection;
$reader->findPropertyType($property, PropertyAccessDirection::Write);// \Stringable|stringA property without a typed set hook gives its read type for both.
Error handling
Section titled “Error handling”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.