Skip to content

php-type-language/reader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP 8.1+ Latest Stable Version Latest Unstable Version License MIT


Converts native PHP types exposed by Reflection objects into TypeLang TypeLang\Type\* AST nodes.

Given a ReflectionClassConstant, ReflectionProperty, ReflectionParameter or ReflectionFunctionAbstract, it returns the matching type node (or null when no type is declared).

Full documentation is available at typelang.dev.

Installation

Install the package via Composer:

composer require type-lang/reader

Requirements:

  • PHP 8.4+

Usage

TypeLang\Reader\ReflectionReader exposes a find*Type() method for every kind of Reflection object:

$reader = new TypeLang\Reader\ReflectionReader();

$node = $reader->findFunctionType(
    new ReflectionFunction(function (): void {}),
);

var_dump($node);
// object(TypeLang\Type\NamedTypeNode) {
//   ["name"] => "void"
//   ...
// }

Combine it with type-lang/printer to dump the resolved types of a whole class:

$class = new ReflectionClass(Path\To\Example::class);
$reader = new TypeLang\Reader\ReflectionReader();
$printer = new TypeLang\Printer\PrettyTypePrinter();

foreach ($class->getProperties() as $property) {
    if ($type = $reader->findPropertyType($property)) {
        echo "property {$property->name}: {$printer->print($type)}\n";
    }
}

foreach ($class->getMethods() as $method) {
    if ($type = $reader->findFunctionType($method)) {
        echo "method {$method->name}(): {$printer->print($type)}\n";
    }
}

Constants (findConstantType()) and parameters (findParameterType()) are read the same way.

About

📰 Library for reading TypeLang AST nodes from types exposed by PHP Reflection objects

Topics

Resources

License

Code of conduct

Stars

6 stars

Watchers

1 watching

Forks

Contributors

Languages