typephp / typephp
Transparent Runtime type checker for PHP. Enforces PHPDoc annotations including generics, typed arrays, array shapes, and advanced types at runtime.
Fund package maintenance!
Requires
- php: ^8.1
- nikic/php-parser: ^5.3
- phpstan/phpdoc-parser: ^2.3
Requires (Dev)
- carthage-software/mago: ^1.47
- friendsofphp/php-cs-fixer: ^3.95
- laravel/pint: ^1.10
- pestphp/pest: ^2.0 || ^3.0 || ^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-strict-rules: ^2.0
- rector/rector: ^2.6
- vimeo/psalm: ^6.16
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v0.14.1
- v0.14.0
- v0.13.3
- v0.13.2
- v0.13.1
- v0.13.0
- v0.12.2
- v0.12.1
- v0.12.0
- v0.11.8
- v0.11.7
- v0.11.6
- v0.11.5
- v0.11.4
- v0.11.3
- v0.11.2
- v0.11.1
- v0.11.0
- v0.10.28
- v0.10.27
- v0.10.26
- v0.10.25
- v0.10.24
- v0.10.23
- v0.10.22
- v0.10.21
- v0.10.20
- v0.10.19
- v0.10.18
- v0.10.17
- v0.10.16
- v0.10.15
- v0.10.14
- v0.10.13
- v0.10.12
- v0.10.11
- v0.10.10
- v0.10.9
- v0.10.8
- v0.10.7
- v0.10.6
- v0.10.5
- v0.10.4
- v0.10.3
- v0.10.2
- v0.10.1
- v0.10.0
- v0.9.1
- v0.9.0
- v0.8.0
- v0.7.6
- v0.7.5
- v0.7.4
- v0.7.3
- v0.7.2
- v0.7.1
- v0.7.0
- v0.6.14
- v0.6.13
- v0.6.12
- v0.6.11
- v0.6.10
- v0.6.9
- v0.6.8
- v0.6.7
- v0.6.6
- v0.6.5
- v0.6.4
- v0.6.3
- v0.6.2
- v0.6.1
- v0.6.0
- v0.5.13
- v0.5.12
- v0.5.11
- v0.5.10
- v0.5.9
- v0.5.8
- v0.5.7
- v0.5.6
- v0.5.5
- v0.5.4
- v0.5.3
- v0.5.2
- v0.5.1
- v0.5.0
- v0.4.3
- v0.4.2
- v0.4.1
- v0.4.0
- v0.3.4
- v0.3.3
- v0.3.2
- v0.3.1
- v0.3.0
- v0.2.2
- v0.2.1
- v0.2.0
- v0.1.8
- v0.1.7
- v0.1.6
- v0.1.5
- v0.1.4
- v0.1.3
- v0.1.2
- v0.1.1
- v0.1.0
- dev-internal-improvements-51
- dev-internal-improvements-50
- dev-internal-improvements-49
- dev-internal-improvements-48
- dev-internal-improvements-47
- dev-internal-improvements-46
- dev-internal-improvements-45
- dev-internal-improvements-44
- dev-internal-improvements-43
- dev-internal-improvements-42
- dev-internal-improvements-41
- dev-internal-improvements-40
- dev-internal-improvements-39
- dev-internal-improvements-38
- dev-internal-improvements-37
- dev-next-minor-released
- dev-internal-improvements-36
- dev-internal-improvements-35
- dev-internal-improvements-34
- dev-internal-improvements-33
- dev-internal-improvements-32
- dev-internal-improvements-31
- dev-internal-improvements-30
- dev-internal-improvements-29
- dev-internal-improvements-28
- dev-improve-test-coverage
- dev-internal-improvements-26
- dev-internal-improvements-25
- dev-fix-promoted-property-errors
- dev-bug-fixes-2
- dev-internal-improvements-24
- dev-internal-improvements-23
- dev-quick-patch-2
- dev-self-out-feature
- dev-prepare-for-minor-bump
- dev-internal-improvements-22
- dev-performance-improvement-3
- dev-internal-improvements-21
- dev-Performace-Improvements
- dev-performance-improvements-2
- dev-reorganize-src-folders
- dev-internal-improvements-20
- dev-internal-improvements-19
- dev-internal-improvements-18
- dev-improve-parallel-testing-compatibility
- dev-internal-improvements-17
- dev-internal-improvements-16
- dev-internal-improvements-15
- dev-experimental-changes
- dev-internal-improvements-14
- dev-internal-improvements-13
- dev-internal-improvements-12
- dev-array-optimization
- dev-performance-optimization
- dev-internal-improvements-11
- dev-expiremental-improvement
- dev-internal-improvements-10
- dev-improve-vendor-isolation-2
- dev-improve-vendor-isolation
- dev-improve-performance
- dev-quick-patch-8
- dev-internal-improvements-9
- dev-quick-patch-7
- dev-internal-improvements-8
- dev-internal-improvements-7
- dev-internal-improvements-6
- dev-quick-patch-6
- dev-internal-improvements-5
- dev-quick-patch-5
- dev-internal-improvements-4
- dev-internal-improvements-3
- dev-quick-patch-4
- dev-internal-improvements-2
This package is auto-updated.
Last update: 2026-11-24 06:52:57 UTC
README
No transpilation. No build steps. No C-extensions.
Drop TypePHP into your existing codebase and let your DocBlocks scream when types fail.
TypePHP is a Fast transparent, pure-PHP runtime type checker. You don't have to refactor a single line of your codebase, set up complex build toolchains, or compile C-extensions. Simply run your existing code, and TypePHP will enforce your extended PHPDoc contracts (generics, array shapes, key-of/value-of extractions, and scalar refinements) dynamically at runtime.
Run in Strict Mode to throw immediate TypeError exceptions, or switch to Audit Report Mode to collect all runtime type violations across your test suites and legacy codebases into structured JSON reports without interrupting execution.
Read the full TypePHP documentation » | Try it online in the Playground »
Try It Online
You can test TypePHP directly in your browser without installing anything locally via the Interactive WebAssembly Playground:
Installation
Install TypePHP as a development dependency via Composer:
composer require typephp/typephp --dev
Note: TypePHP boots automatically via Composer's autoloader. No service providers, bootstrap edits, or framework configurations are required.
Quick Start
1. Initialize Configuration (Optional)
Generate a default typephp.php configuration file in your project root:
vendor/bin/typephp config:init
2. Write Standard DocBlocks
Annotate your functions, methods, and classes with standard static analysis DocBlocks:
namespace App\Services; class PaymentService { /** * @param positive-int $amount * @param array{gateway: 'stripe'|'paypal', currency: non-empty-string} $options * @return non-empty-string */ public function charge(int $amount, array $options): string { return "Transaction successful"; } }
3. Run Your Application or Tests
If your application runs through an entry point where require 'vendor/autoload.php' is declared (such as a web framework's public/index.php, CLI commands, or test runners like Pest and PHPUnit), TypePHP runs automatically and transparently in the background.
Simply run your tests or use your local development server (Laravel, Symfony, FrankenPHP, PHP-FPM). TypePHP immediately intercepts and enforces all parameter, return, shape, and generic contracts in real time.
Executing Standalone Scripts (CLI Runner)
You can run any standalone PHP script directly with the TypePHP CLI binary:
vendor/bin/typephp script.php
Targeting a file directly with the CLI binary automatically type-checks that file even if it is not registered in typephp.php or falls outside your configured include paths.
Any secondary files required or included by your script will continue to respect your project's configured include and exclude paths.
Type-Checking Files Anywhere ("*" Wildcard Glob)
By default, TypePHP checks standard application folders (src/**, app/**, tests/**). To type-check PHP files anywhere in your project root during regular application runs while still respecting your excluded folders, set the "*" wildcard glob in typephp.php:
// typephp.php return [ 'include' => [ '*', ], 'exclude' => [ 'vendor/**', 'storage/**', 'var/**', 'cache/**', ], ];
Live Diagnostics (Zero Line-Drift)
When a type contract fails, web exception handlers (Laravel Ignition, Symfony ErrorHandler, Whoops) and CLI test runners (Pest, PHPUnit) highlight the exact line of code in your application where the invalid data was passed, with zero line-drift:
Web Framework Trace (Laravel Ignition)
Web Framework Trace (Symfony ErrorHandler)
CLI Test Runner Trace (Pest PHP)
See It In Action
1. Framework Boundary Protection (Laravel / Symfony)
Prevent dynamic data bugs from leaking into database queries or API responses:
namespace App\Models; use App\Enums\Role; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * @return list<int> */ public function assignableRoles(): array { if ($this->isSuperAdmin()) { // Bug! Returns an array of Role Enum instances instead of integers: return Role::cases(); } return [Role::STAFF->value]; } } // Executing $user->assignableRoles() throws: // TypePHP\Exception\TypeError: User::assignableRoles(): Return value[0] must be of type int, App\Enums\Role returned
2. True Runtime Generics with Memory State
Define generic templates and TypePHP tracks their state per object instance in memory using native \WeakMap:
/** * @template T */ class Collection { /** @param T $item */ public function add(mixed $item): void { } } // Prebind T = User to this specific instance in WeakMap memory /** @var Collection<User> $users */ $users = new Collection(); $users->add(new User('Alice')); $users->add(new Product('SKU-100')); // Throws TypeError: Argument $item (template T = User) must be of type User, Product given
3. Array Shapes & Constant Extractions
Enforce strict associative array structures and constant key/value extractions:
namespace App\Services; use App\Database\DriverManager; /** * @phpstan-type ConnectionParams array{ * driver: key-of<DriverManager::DRIVER_MAP>, * driverClass?: value-of<DriverManager::DRIVER_MAP> * } */ class DatabaseService { /** * @param ConnectionParams $params */ public function connect(array $params): void { // ... } } $service = new DatabaseService(); $service->connect(['driver' => 'pdo_mysql']); $service->connect(['driver' => 'pdo_invalid']); // Throws TypeError: Argument $params['driver'] must be a key of DriverManager::DRIVER_MAP
4. Zero-Crash Audit & Reporting Mode (CI/CD Quality Gates)
Audit legacy codebases, massive monolithic applications, or staging environments without crashing execution:
// typephp.php return [ 'on_violation' => 'report', // 'throw' | 'report' | 'warn' 'report_file' => 'var/typephp-report.json', 'fail_on_report' => true, // Terminates with exit code 1 at shutdown if violations exist 'redact_values' => true, // Masks raw values for GDPR / HIPAA compliance ];
Run your full test suite or application normally, then inspect the formatted violation report directly in your terminal:
vendor/bin/typephp report
TYPEPHP Violation Audit Report
• Total Violations: 2
• Files Affected: 1
• Report Source: var/typephp-report.json
src/Services/OrderService.php
Line 42 parameter $amount expected positive-int, int given
Line 88 return return expected non-empty-string, string given
Supports parallel test runners (ParaTest, Pest Parallel) with automatic process-isolated worker sharding and lock-free report consolidation.
Performance: Unbearably Fast Runtime Enforcement
Runtime type checking in pure PHP shouldn't force you to choose between strictness and speed. TypePHP combines compile-time AST elimination, AST-inlined fast-path guards, precompiled opcode plans, bitmask template inference, and optional O(1) hybrid array sampling and delivering blazing-fast execution even on the heaviest generic codebases.
Real-World Stress Benchmark (noctud/collection)
Tested against noctud/collection (6,928 tests, 12,510 assertions) this a worst-case, pure-CPU benchmark packed with @template inference, variance rules, WeakMap reified generics, conditional return types, fluent self<T> chains, iterables, and closures:
| Mode | Native PHP (TYPEPHP_DISABLE=true) |
Early TypePHP | TypePHP Now | Wall-Time Speedup | Overhead Eliminated |
|---|---|---|---|---|---|
Sequential (phpunit) |
00:06.554 (82 MB) |
02:41.013 (108 MB) |
00:29.440 (128 MB) |
5.47× faster | −85.2% (154.5s → 22.9s) |
Parallel (paratest -p4) |
00:02.001 (62 MB) |
01:26.168 (62 MB) |
00:07.780 (62 MB) |
11.08× faster | −93.1% (84.2s → 5.8s) |
Running full runtime generics and PHPDoc contract enforcement across nearly 7,000 collection tests completes in under 8 seconds in parallel and adding less than 6 seconds over raw native PHP.
How TypePHP Stays Fast
- Compile-Time Static Elimination: Provably satisfied contracts (literals, trusted unmutated parameters, constants, exact non-generic instantiations) are eliminated during AST transformation and costing 0 ns at runtime.
- AST-Inlined Guards & Disk Caching: Transformed files are cached to disk (and OPcache-ready) with inline
isset()short-circuits so unconstrained or non-contracted methods skip runtime calls entirely. - Precompiled Opcode Plans & Flat Call Frames: Parameter, return,
class-string<T>, and generic iterable checks execute against precompiled integer opcodes, bitmasks, and flat O(1) frame arrays rather than re-interpreting DocBlock ASTs. - Configurable Array Strategy (
fullvshybrid): Use'array_validation' => 'full'for 100% exhaustive O(n) scans, or switch to'hybrid'for Beartype-inspired O(1) boundary + random sampling on massive arrays (> 128items).
Documentation
All the documentation lives on the typephp.dev website:
- Interactive Playground
- Getting Started & Installation Guide
- Quick Start Guide
- Configuration Guide
- Audit Reporting & CI/CD Gates
- CLI Commands Reference
- Runtime Generics (Flagship)
- Enforcement Boundaries: Function Contracts
- Supported Types: Arrays & Shapes
- Architecture: How It Works
- Official Blog & Announcements
- Troubleshooting & FAQ
Credits & Special Thanks
TypePHP stands on the shoulders of giants. It simply would not exist without these foundational tools and supporters of the PHP ecosystem:
- PHPStan &
phpstan/phpdoc-parser(created by Ondřej Mirtes and contributors): A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP,phpstan/phpdoc-parseris the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory including reified generics (@template), conditional types, intersection/union types, DNF, array shapes, and variance directly at runtime. nikic/php-parser(created by Nikita Popov): The gold standard for PHP abstract syntax tree (AST) parsing and code manipulation. It powers TypePHP's transparent stream wrapper interception, format-preserving AST transformations, and zero line-drift instrumentation.- Blackfire: A huge thank you to Blackfire for generously providing a free 1-year open-source subscription for TypePHP. Blackfire's deterministic call-graph and memory profiling made it possible to hunt down hot-path bottlenecks and achieve up to an 11× speedup on generics-heavy workloads.
php-spx: Many thanks to thephp-spxPHP profiling extension—its lightweight flamegraphs, flat execution profiles, and built-in web UI were instrumental in pinpointing tight-loop overhead and tuning TypePHP's runtime engine.
Inspiration
TypePHP is conceptually inspired by Python's Beartype and Typeguard, bringing transparent runtime type enforcement for type annotations to the PHP ecosystem without decorators or attributes.
Sponsors
Want to support the open-source development and maintenance of TypePHP? Sponsor me on GitHub »
Contributing
Any contributions are welcome. Feel free to open issues or submit pull requests on GitHub.
License
TypePHP is open-source software licensed under the MIT License.


