$ show pinkary-project/type-guard
A PHP library that provides a type-safe, static analysis-friendly way to narrow down mixed or union types at runtime. The core is a `Type` class (entry point via `type()` helper) that offers methods like `asString()`, `asInt()`, `as(ClassName::class)`, etc., each performing a runtime assertion and returning the narrowed type. It leverages PHPStan/Psalm's `@phpstan-assert-if-true` annotations to allow static analyzers to infer the narrowed type, preserving generic type information (e.g., `Collection<int, User>`). The library includes a `Not` class for negation checks (e.g., `type($x)->not()->null()`). It is part of the Pinkary Project, requires PHP 8.2+, and has zero runtime dependencies. The source is meticulously crafted with full test coverage, type-strict coding, and continuous integration enforcing linting, static analysis, and type coverage. It is a model example of how to expose runtime assertion functions with first-class static analysis support.
The LLM identified 2 files worth highlighting for reuse:
Core class implementing type assertions with runtime checks and PHPStan/Psalm annotations for static type narrowing. Each method (asString, asInt, asArray, etc.) uses `@phpstan-assert-if-true` to inform static analyzers of the narrowed type. The generic `as(string $type)` method preserves full generic type information (e.g., `QueryBuilder<User>`). The class is self-contained, with no internal dependencies, and can be extracted into any PHP project requiring type-safe casting from mixed/union types.
Companion class for negated type assertions, accessed via `Type::not()`. Currently implements `null()` to assert a variable is not null. Uses `@phpstan-assert-if-true !null` and returns the variable with the null type removed. Demonstrates a clean API for type negation, reusable across projects to eliminate nullable types in a static-analysis-friendly way.