koriym/var-type

0.1.0 2024-07-04 18:05 UTC

This package is auto-updated.

Last update: 2024-10-07 07:22:33 UTC


README

Continuous Integration

var type logo

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, ...}
  • Objects (object-like arrays): ClassName{property1: type1, property2: type2, ...}

Why VarType?

  1. Enhanced Static Analysis: VarType provides detailed type information that can be used with tools like Psalm and PHPStan for more accurate static analysis.

  2. Improved IDE Support: The detailed type strings generated by VarType can enhance IDE autocompletion and type inference, making development more efficient.

  3. 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.

  4. Debugging Aid: Quickly understand the structure of complex variables, including nested object-like arrays and array shapes.

  5. Documentation: Generate precise type information for APIs or function parameters, improving code readability and maintainability.

VarType - Unleash the full potential of PHP type information!