Skip to content

Commit 6d66d3e

Browse files
committed
Update documentation to include @param-out in function boundary contracts and configuration
1 parent fe3daa5 commit 6d66d3e

2 files changed

Lines changed: 62 additions & 70 deletions

File tree

‎docs/core-concepts/function-contracts.md‎

Lines changed: 47 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Function Contracts
22

3-
Functions and methods form the public boundaries of your software modules. TypePHP enforces `@param` and `@return` annotations directly at function entry and exit points.
3+
Functions and methods form the public boundaries of your software modules. TypePHP enforces `@param`, `@param-out`, and `@return` annotations directly at function entry and exit points.
44

55
---
66

@@ -68,8 +68,6 @@ By default (`'respect_native_nullability' => true`), TypePHP merges native param
6868

6969
> **Native `?array`** + **DocBlock `string[]`** $\rightarrow$ **Effective Contract: `?string[]` (`string[]|null`)**
7070
71-
This provides complete type safety without breaking real-world code:
72-
7371
This provides complete type safety without breaking real-world code:
7472
* **Passing `null` (or omitting default argument):** Accepted cleanly.
7573
* **Passing `['admin', 'editor']`:** Accepted, and every element is verified as a valid string.
@@ -123,14 +121,15 @@ $$\text{1. } \mathbf{@phpstan\text{-}*} \quad \longrightarrow \quad \text{2. } \
123121

124122
### Why Priority Matters in Real-World Codebases
125123

126-
1. **Refined Contracts Take Precedence:** Tool-specific annotations (`@phpstan-param`, `@psalm-return`) contain specific type constraints (such as generic templates, array shapes, or integer bounds) that standard `@param mixed` omits. TypePHP always enforces the tighter, intended contract.
124+
1. **Refined Contracts Take Precedence:** Tool-specific annotations (`@phpstan-param`, `@phpstan-param-out`, `@psalm-return`) contain specific type constraints (such as generic templates, array shapes, or integer bounds) that standard `@param mixed` omits. TypePHP always enforces the tighter, intended contract.
127125
2. **Third-Party Framework Compatibility:** Libraries like Doctrine Collections declare `@phpstan-param T $element` on `Collection::add` alongside native `mixed $element`. TypePHP automatically prioritizes `@phpstan-param`, making generic collections enforce types at runtime without manual wrapper code.
128126

129127
### Tooling Priority Matrix Across Boundary Contracts
130128

131129
| Boundary Type | Priority 1 (Highest) | Priority 2 | Priority 3 (Fallback) |
132130
| :--- | :--- | :--- | :--- |
133-
| **Parameters** | `@phpstan-param` | `@psalm-param` | `@param` |
131+
| **Parameters (Input)** | `@phpstan-param` | `@psalm-param` | `@param` |
132+
| **Out-Parameters (Exit)** | `@phpstan-param-out` | `@psalm-param-out` | `@param-out` |
134133
| **Return Values** | `@phpstan-return` | `@psalm-return` | `@return` |
135134

136135
---
@@ -168,11 +167,11 @@ registerUser(age: 25, username: 'Alice', id: -5);
168167

169168
TypePHP natively supports PHP's by-reference parameter semantics (`function update(int &$value)`).
170169

171-
### How By-Reference Validation Works
170+
### How By-Reference Input Validation Works (`@param`)
172171

173172
1. **Entry Guard Rails:** TypePHP inspects and validates the variable's value *on function entry* before the function body executes.
174173
2. **In-Place Caller Scope Mutation:** If the argument passes validation, the function body executes normally, and any modifications to the variable mutate the caller's variable in the caller's scope.
175-
3. **Safety Guarantee on Failure:** If an invalid value is passed into a by-reference parameter, a `TypeError` is thrown *before* any code in the function body runs, ensuring the caller's variable remains **100% un-mutated and un-corrupted**.
174+
3. **Safety Guarantee on Failure:** If an invalid value is passed into a by-reference parameter on entry, a `TypeError` is thrown *before* any code in the function body runs, ensuring the caller's variable remains **100% un-mutated and un-corrupted**.
176175

177176
```php
178177
<?php
@@ -227,88 +226,73 @@ function incrementCount(int &$count): void { $count++; }
227226
function incrementCount(int &$count): void { $count++; }
228227
```
229228

230-
### By-Reference Arrays & Shapes
229+
---
230+
231+
## By-Reference Out-Parameter Contracts (`@param-out`)
231232

232-
Mutating collections or array shapes in-place preserves caller scope bindings:
233+
While `@param` enforces pre-conditions on function entry, **`@param-out`** (and `@phpstan-param-out` / `@psalm-param-out`) enforces **post-conditions on function exit**.
234+
235+
When a function mutates a by-reference variable, TypePHP validates the variable's value right before the function returns or exits.
233236

234237
```php
235238
/**
236-
* @param list<positive-int> &$scores
239+
* On entry: $value can be anything (mixed)
240+
* On exit: $value is guaranteed to be a positive integer
241+
*
242+
* @param mixed &$value
243+
* @param-out positive-int $value
237244
*/
238-
function appendReward(array &$scores): void
245+
function initializeIdentifier(mixed &$value): void
239246
{
240-
$scores[] = 500; // Mutates array in caller scope
247+
$value = 42; // Valid mutation
241248
}
242249

243-
$myScores = [10, 20, 30];
244-
appendReward($myScores);
245-
246-
print_r($myScores); // [10, 20, 30, 500]
247-
```
250+
$id = null;
251+
initializeIdentifier($id);
252+
echo $id; // Output: 42
248253

249-
### Variadic By-Reference Parameters (`&...$params`)
250-
251-
When accepting a variable number of by-reference arguments (`int &...$numbers`), TypePHP validates every individual argument on entry and preserves in-place mutations across all variadic arguments:
252-
253-
```php
254254
/**
255-
* @param positive-int &...$numbers
255+
* Failing Out-Parameter Example
256+
*
257+
* @param mixed &$value
258+
* @param-out positive-int $value
256259
*/
257-
function doubleAll(int &...$numbers): void
260+
function badInitialize(mixed &$value): void
258261
{
259-
foreach ($numbers as &$num) {
260-
$num *= 2;
261-
}
262+
$value = -50; // Invalid: Violates positive-int!
262263
}
263264

264-
$a = 5;
265-
$b = 10;
266-
$c = 15;
267-
268-
doubleAll($a, $b, $c);
269-
270-
echo "$a, $b, $c"; // Output: 10, 20, 30
265+
$code = 'init';
266+
badInitialize($code);
267+
// Throws: TypeError: badInitialize(): Argument &$value (param-out) must be of type positive-int, negative int (-50) given
271268
```
272269

273-
### OOP & Interface Inheritance for By-Reference Parameters
270+
### Full Type Algebra Support in `@param-out`
274271

275-
When a child class implements an interface or overrides a parent method with by-reference parameters, the type contract and reference semantics are inherited automatically (even when child methods rename parameters):
272+
`@param-out` supports all advanced types available in TypePHP:
273+
* **Refinements:** `@param-out non-empty-string $token`
274+
* **Array Shapes:** `@param-out array{id: positive-int, token: non-empty-string} $payload`
275+
* **Unions & Intersections:** `@param-out ('active'|'pending') $status`, `@param-out (Countable&ArrayAccess) $collection`
276+
* **Generic Templates:** `@param-out T $output`
276277

277-
```php
278-
interface StatusUpdaterInterface
279-
{
280-
/**
281-
* @param non-empty-string &$status
282-
* @param positive-int &$code
283-
*/
284-
public function update(string &$status, int &$code): void;
285-
}
278+
### Disabling Out-Parameter Checks Independently
286279

287-
class StatusUpdater implements StatusUpdaterInterface
288-
{
289-
// Inherits contracts and by-reference semantics seamlessly
290-
public function update(string &$status, int &$statusCode): void
291-
{
292-
$status = strtoupper($status);
293-
$statusCode += 100;
294-
}
295-
}
296-
297-
$updater = new StatusUpdater();
298-
$currentStatus = 'pending';
299-
$currentCode = 200;
280+
You can independently enable or disable `@param-out` enforcement using the `'params_out'` configuration key in `typephp.php`:
300281

301-
$updater->update($currentStatus, $currentCode);
302-
303-
echo $currentStatus; // 'PENDING'
304-
echo $currentCode; // 300
282+
```php
283+
// typephp.php
284+
return [
285+
'params' => true, // Enforces @param on entry
286+
'returns' => true, // Enforces @return
287+
'params_out' => true, // Set to false to disable @param-out exit validation
288+
];
305289
```
306290

307291
---
308292

309293
## Class Methods (Instance & Static)
310294

311-
All parameter and return contract rules apply identically to **instance methods** (`public`, `protected`, `private`) and **static methods**:
295+
All parameter, return, and out-parameter contract rules apply identically to **instance methods** (`public`, `protected`, `private`) and **static methods**:
312296

313297
```php
314298
class UserService

‎docs/getting-started/configuration.md‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,14 @@ return [
2727

2828
/*
2929
|--------------------------------------------------------------------------
30-
| Function Boundary Contracts (@param & @return)
30+
| Function Boundary Contracts (@param, @return, @param-out)
3131
|--------------------------------------------------------------------------
32-
| Enforces function and method parameter and return type contracts uniformly.
32+
| Enforces function and method parameter, return, and by-reference
33+
| out-parameter contracts uniformly.
3334
*/
34-
'params' => true,
35-
'returns' => true,
35+
'params' => true,
36+
'returns' => true,
37+
'params_out' => true,
3638

3739
/*
3840
|--------------------------------------------------------------------------
@@ -115,9 +117,13 @@ return [
115117
| it uses your system's temp directory. You can change this to a path
116118
| inside your project (e.g., __DIR__ . '/storage/framework/typephp').
117119
| TypePHP automatically protects this directory from being double-transformed.
120+
|
121+
| 'cache_check_mtime' controls file modification checks. Keep true in dev.
122+
| Set to false in production to eliminate all disk stat() calls.
118123
*/
119-
'cache' => true,
120-
'cache_dir' => null,
124+
'cache' => true,
125+
'cache_dir' => null,
126+
'cache_check_mtime' => true,
121127

122128
/*
123129
|--------------------------------------------------------------------------
@@ -195,6 +201,7 @@ return [
195201
| **`'enabled'`** | `true` | Global master switch for runtime type enforcement. |
196202
| **`'params'`** | `true` | Enforces parameter `@param` contracts on functions and methods. |
197203
| **`'returns'`** | `true` | Enforces return `@return` contracts on functions and methods. |
204+
| **`'params_out'`** | `true` | Enforces by-reference out-parameter `@param-out` post-conditions on function and method exits. |
198205
| **`'strict_return_generic_invariance'`** | `true` | Enforces strict generic return invariance matching PHPStan Level MAX (e.g. returning `Collection<Dog>` where `Collection<Animal>` is expected is rejected unless `@template-covariant` or `<covariant Animal>` is specified). Set to `false` (pragmatic mode) for frameworks (Laravel, Shopware) where collection classes omit covariance annotations. |
199206
| **`'vendor_boundary_only'`** | `true` | When `true` (default), whitelisted vendor classes (e.g. `Illuminate\Support\Collection`) only enforce type contracts when called from application code (`app/**`, `src/**`, `tests/**`). Calls originating from excluded vendor files or internal self-calls bypass strict checking. Set to `false` for strict pedantic auditing across all vendor code. |
200207
| **`'respect_ignore_tags'`** | `true` | Respects `@typephp-ignore` and `@typephp-ignore-file` tags. Set to `false` in CI/CD to force audit checks. |
@@ -204,6 +211,7 @@ return [
204211
| **`'array_validation'`** | `'full'` | Validation strategy for collections: `'full'` (exhaustive $O(n)$) or `'hybrid'` (Beartype $O(1)$ sampling for $> 128$ items). |
205212
| **`'cache'`** | `true` | Pre-transforms and caches PHP files on disk. Set to `false` to transform files purely in memory (`php://memory`). |
206213
| **`'cache_dir'`** | `null` | Custom path to store cached files. Defaults to system temporary directory (`sys_get_temp_dir() . '/typephp-cache/'`). |
214+
| **`'cache_check_mtime'`** | `true` | When `true` (default), checks `@filemtime` on file load to automatically rebuild the cache when source files change. Set to `false` in production to eliminate all disk `stat()` calls for maximum throughput via OPcache. |
207215
| **`'extensions'`** | `[]` | Explicit list of third-party extension classes implementing `ExtensionInterface`. |
208216
| **`'stubs'`** | `[]` | Path globs pointing to `.stub` files that override third-party vendor DocBlocks. |
209217
| **`'inline_vars'`** | `[...]` | Fine-grained configuration for local `@var` variable validations. |
@@ -272,4 +280,4 @@ $$\text{Winning Rule} = \max(\text{Pattern Length})$$
272280
To disable TypePHP immediately without modifying application code:
273281

274282
1. **Environment Level (Zero Overhead):** Set `TYPEPHP_DISABLE=true` in your server environment or `.env` file before autoloading.
275-
2. **Config Level (Pass-Through):** Set `'enabled' => false` in `typephp.php` or call `TypePHP::setConfig(['enabled' => false])`.
283+
2. **Config Level (Pass-Through):** Set `'enabled' => false` in `typephp.php` or call `TypePHP::setConfig(['enabled' => false])`.

0 commit comments

Comments
 (0)