koriym / var-type
Requires
- php: ^8.0
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.8
- phpunit/phpunit: ^9.6.19
README
VarType is a powerful PHP library that generates detailed type information from PHP variables, with a focus on producing "object-like array" and "array shape" representations. It's designed to enhance static analysis capabilities and improve IDE autocompletion and type inference.Features
- Generate detailed type information for any PHP variable
- Produce "object-like array" and "array shape" representations
- Support for arrays, objects, and scalar types
- Distinguish between indexed arrays and associative arrays (array shapes)
- Recursively analyze nested structures
- Compatible with static analysis tools like Psalm and PHPStan
- Enhance IDE autocompletion and type prediction
Installation
Install VarType using Composer:
composer require --dev koriym/var-type
Usage
Here's a quick example of VarType in action:
use Koriym\VarType\VarType; $data = [ 'user' => [ 'name' => 'John Doe', 'age' => 30, 'skills' => ['PHP', 'JavaScript', 'Python'], ], 'settings' => (object)['theme' => 'dark', 'notifications' => true] ]; VarType::dump($data);
This will output:
array{user: array{name: string, age: int, skills: array<string>}, settings: stdClass{theme: string, notifications: bool}}
Advanced Usage
You can also use the VarType class as an invokable:
$varType = new VarType(); echo $varType($data);
Type Representations
VarType uses the following syntax to represent different types:
- Scalar types:
int
,float
,bool
,string
,null
- Arrays:
- Indexed arrays:
array<type1|type2|...>
- Associative arrays (array shapes):
array{key1: type1, key2: type2, ...}
- Indexed arrays:
- Objects (object-like arrays):
ClassName{property1: type1, property2: type2, ...}
Why VarType?
-
Enhanced Static Analysis: VarType provides detailed type information that can be used with tools like Psalm and PHPStan for more accurate static analysis.
-
Improved IDE Support: The detailed type strings generated by VarType can enhance IDE autocompletion and type inference, making development more efficient.
-
Detailed Type Information: While PHP's built-in functions can provide basic type information, VarType offers much more detailed type representations, including object-like arrays and array shapes.
-
Debugging Aid: Quickly understand the structure of complex variables, including nested object-like arrays and array shapes.
-
Documentation: Generate precise type information for APIs or function parameters, improving code readability and maintainability.
VarType - Unleash the full potential of PHP type information!