Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@
/.php-cs-fixer.dist.php export-ignore
/codecov.yml export-ignore
/rector.php export-ignore
/typephp.php export-ignore
/typephp.php export-ignore
/README.md export-ignore
/CONTRIBUTING.md export-ignore
/SECURITY.md export-ignore
27 changes: 19 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

---

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

Expand Down Expand Up @@ -262,23 +262,34 @@ Supports parallel test runners (**ParaTest**, **Pest Parallel**) with automatic

## 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.
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** to deliver blazing-fast execution on both everyday web applications and heavy generic libraries.

### Real-World Stress Benchmark ([`noctud/collection`](https://github.com/noctud/collection))
### Real-World Laravel Application (Typical I/O-Bound Workload)

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:
Tested on a real-world Laravel application (**430 tests, 2,652 assertions**, **216 instrumented application files** running via `php artisan test --compact` with warm cache):

| Mode | Duration | Overhead |
| --- | --- | --- |
| **TypePHP Disabled (`TYPEPHP_DISABLE=true`)** | `54.46s` | — |
| **TypePHP Enabled** | `55.12s` | **`+0.66s` (~1.2%)** |

In typical web frameworks (**Laravel**, **Symfony**, **Shopware**) where database queries, HTTP routing, container bootstrapping, and I/O dominate execution time, TypePHP's runtime overhead is **negligible (~1%)**—practically indistinguishable from normal run-to-run variance.

### Pure-CPU Stress Benchmark ([`noctud/collection`](https://github.com/noctud/collection))

Tested against `noctud/collection` (**6,928 tests, 12,510 assertions**) this is a worst-case, pure-CPU benchmark with zero I/O, packed with `@template` inference, variance rules, `WeakMap` reified generics, conditional return types, fluent `self<T>` chains, typed iterables, and typed 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`) |
| **Sequential (`phpunit`)** | `00:06.554` (`82 MB`) | `02:41.013` (`108 MB`) | `00:23.463` (`130 MB`) | **6.86× faster** | **−89.1%** (`154.5s` → `16.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.
Even in this extreme pure-CPU generics stress test, running full runtime reified generics and PHPDoc contract enforcement across nearly 7,000 collection tests completes in **under 8 seconds** in parallel, 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.
* **Compile-Time Static Elimination:** Provably satisfied contracts (literals, trusted unmutated parameters, constants, exact non-generic instantiations) are eliminated during AST transformation, 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.
* **Precompiled Opcode Plans & Flat Call Frames:** Parameter, return, `class-string<T>`, and generic iterable checks execute against precompiled local integer opcodes (`ZEND_MATCH` jump tables), bitmasks, and flat O(1) frame arrays rather than re-interpreting DocBlock ASTs.
* **Configurable Array Strategy (`full` vs `hybrid`):** 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 (`> 128` items).

---
Expand Down
20 changes: 20 additions & 0 deletions src/Internal/Generics/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -1634,6 +1634,26 @@ public static function bindInstanceFromNode(
self::resolveInheritedTemplates($instance, $className);
}

if (! $forceBind && ! $allowBoundSpecialization && ! $refineOnly) {
$defaults = self::$classTemplateDefaultsCache[$actualClass] ?? self::classTemplateDefaults($actualClass);
if ($defaults !== []) {
self::$instanceTemplateBindings ??= new WeakMap();
$currentInstBindings = self::$instanceTemplateBindings[$instance] ?? [];
$defaultsApplied = false;

foreach ($defaults as $defName => $defType) {
if (! isset($currentInstBindings[$defName])) {
$currentInstBindings[$defName] = $defType;
$defaultsApplied = true;
}
}

if ($defaultsApplied) {
self::$instanceTemplateBindings[$instance] = $currentInstBindings;
}
}
}

$existingBindings = self::$instanceTemplateBindings !== null
? (self::$instanceTemplateBindings[$instance] ?? null)
: null;
Expand Down
176 changes: 167 additions & 9 deletions src/Internal/Reporting/ViolationCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ final class ViolationCollector

private static bool $shutdownRegistered = false;

/**
* Tracks how many occurrences of each violation hash this process has already merged
* into a given report file path, preventing double-counting on repeated exportReport() calls.
*
* @var array<string, array<string, int>>
*/
private static array $exportedCountsByTarget = [];

/**
* Resets in-memory state. Useful for test isolation.
*/
Expand All @@ -49,6 +57,7 @@ public static function reset(): void
self::$violations = [];
self::$warnedHashes = [];
self::$propertyLineCache = [];
self::$exportedCountsByTarget = [];
self::$shutdownRegistered = false;
}

Expand Down Expand Up @@ -167,6 +176,7 @@ public static function clear(): void
self::$violations = [];
self::$warnedHashes = [];
self::$propertyLineCache = [];
self::$exportedCountsByTarget = [];
}

/**
Expand Down Expand Up @@ -275,7 +285,8 @@ public static function writeWorkerShard(string $reportFile): void
}

/**
* Merges in-memory violations with any worker shards and atomically exports the master report JSON.
* Merges in-memory violations, any existing report on disk, and worker shards
* under an exclusive file lock, then writes the consolidated master report JSON.
*/
public static function exportReport(?string $filePath = null): ?string
{
Expand All @@ -287,22 +298,169 @@ public static function exportReport(?string $filePath = null): ?string
$reportDir = \dirname($targetFile);
$shardDir = $reportDir . '/.typephp-shards';

$allViolations = self::consolidateShards(self::$violations, $shardDir);

if (! is_dir($reportDir)) {
@mkdir($reportDir, 0777, true);
}

$document = self::buildReportDocument($allViolations);
$json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
$normalizedTarget = str_replace('\\', '/', $targetFile);
$fp = @fopen($targetFile, 'c+b');

if ($json === false || @file_put_contents($targetFile, $json) === false) {
return null;
if ($fp === false) {
$allViolations = self::consolidateShards(self::$violations, $shardDir);
$document = self::buildReportDocument($allViolations);
$json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);

if ($json === false || @file_put_contents($targetFile, $json) === false) {
return null;
}

return $targetFile;
}

$locked = @flock($fp, LOCK_EX);

try {
$existingViolations = [];
$existingInstrumentedCount = 0;

rewind($fp);
$existingRaw = stream_get_contents($fp);
if (\is_string($existingRaw) && trim($existingRaw) !== '') {
[$existingViolations, $existingInstrumentedCount] = self::parseExistingReport($existingRaw);
}

$hadShards = is_dir($shardDir);
$hasNewDeltas = false;
$merged = $existingViolations;
$exportedForTarget = self::$exportedCountsByTarget[$normalizedTarget] ?? [];

foreach (self::$violations as $hash => $record) {
$alreadyExported = $exportedForTarget[$hash] ?? 0;
$delta = $record->count - $alreadyExported;

if ($delta > 0) {
$hasNewDeltas = true;
if (isset($merged[$hash])) {
$merged[$hash] = $merged[$hash]->withIncrementedCount($delta);
} else {
$merged[$hash] = $delta === $record->count
? $record
: new ViolationRecord(
file: $record->file,
line: $record->line,
function: $record->function,
kind: $record->kind,
target: $record->target,
expected: $record->expected,
given: $record->given,
message: $record->message,
count: $delta,
caller: $record->caller,
declaredIn: $record->declaredIn
);
}
$exportedForTarget[$hash] = $record->count;
} elseif (! isset($merged[$hash])) {
$hasNewDeltas = true;
$merged[$hash] = $record;
$exportedForTarget[$hash] = $record->count;
}
}

self::$exportedCountsByTarget[$normalizedTarget] = $exportedForTarget;

$allViolations = self::consolidateShards($merged, $shardDir);
$instrumentedCount = max($existingInstrumentedCount, StreamWrapper::getInstrumentedCount());

if (
\is_string($existingRaw)
&& trim($existingRaw) !== ''
&& ! $hasNewDeltas
&& ! $hadShards
&& $instrumentedCount === $existingInstrumentedCount
) {
return $targetFile;
}

$document = self::buildReportDocument($allViolations, $instrumentedCount);
$json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);

if ($json === false) {
return null;
}

rewind($fp);
ftruncate($fp, 0);
$written = fwrite($fp, $json);
fflush($fp);

if ($written === false) {
return null;
}
} finally {
if ($locked) {
@flock($fp, LOCK_UN);
}
fclose($fp);
}

return $targetFile;
}

/**
* Parses an existing master report JSON payload into deduplicated records and its instrumented file count.
*
* @return array{0: array<string, ViolationRecord>, 1: int}
*/
private static function parseExistingReport(string $raw): array
{
/** @var array<string, mixed>|null $decoded */
$decoded = json_decode($raw, true);
if (! \is_array($decoded)) {
return [[], 0];
}

/** @var array<string, ViolationRecord> $violations */
$violations = [];
if (isset($decoded['violations']) && \is_array($decoded['violations'])) {
foreach ($decoded['violations'] as $item) {
if (! \is_array($item)) {
continue;
}

/** @var array<string, mixed> $item */
$record = ViolationRecord::fromArray($item);
if ($record === null) {
continue;
}

$hash = $record->getHash();
$violations[$hash] = isset($violations[$hash])
? $violations[$hash]->withIncrementedCount($record->count)
: $record;
}
}

$instrumentedCount = 0;
if (
isset($decoded['summary'])
&& \is_array($decoded['summary'])
&& isset($decoded['summary']['files_instrumented'])
&& \is_int($decoded['summary']['files_instrumented'])
) {
$instrumentedCount = max(0, $decoded['summary']['files_instrumented']);
} elseif (
isset($decoded['context'])
&& \is_array($decoded['context'])
&& isset($decoded['context']['files_instrumented'])
&& \is_int($decoded['context']['files_instrumented'])
) {
$instrumentedCount = max(0, $decoded['context']['files_instrumented']);
}

return [$violations, $instrumentedCount];
}

/**
* @param array<string, ViolationRecord> $baseViolations
*
Expand Down Expand Up @@ -392,15 +550,15 @@ private static function mergeShardContent(array $allViolations, string $raw): ar
* violations: list<ViolationRecord>
* }
*/
private static function buildReportDocument(array $violations): array
private static function buildReportDocument(array $violations, ?int $instrumentedCount = null): array
{
$violationsList = array_values($violations);
$filesAffected = [];
foreach ($violationsList as $v) {
$filesAffected[$v->file] = true;
}

$instrumentedCount = StreamWrapper::getInstrumentedCount();
$instrumentedCount ??= StreamWrapper::getInstrumentedCount();
$configFile = Config::getResolvedConfigFile();
$projectRoot = Config::getProjectRoot();

Expand Down
Loading
Loading