|
1 | 1 | # Function Contracts |
2 | 2 |
|
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. |
4 | 4 |
|
5 | 5 | --- |
6 | 6 |
|
@@ -68,8 +68,6 @@ By default (`'respect_native_nullability' => true`), TypePHP merges native param |
68 | 68 |
|
69 | 69 | > **Native `?array`** + **DocBlock `string[]`** $\rightarrow$ **Effective Contract: `?string[]` (`string[]|null`)** |
70 | 70 |
|
71 | | -This provides complete type safety without breaking real-world code: |
72 | | - |
73 | 71 | This provides complete type safety without breaking real-world code: |
74 | 72 | * **Passing `null` (or omitting default argument):** Accepted cleanly. |
75 | 73 | * **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. } \ |
123 | 121 |
|
124 | 122 | ### Why Priority Matters in Real-World Codebases |
125 | 123 |
|
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. |
127 | 125 | 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. |
128 | 126 |
|
129 | 127 | ### Tooling Priority Matrix Across Boundary Contracts |
130 | 128 |
|
131 | 129 | | Boundary Type | Priority 1 (Highest) | Priority 2 | Priority 3 (Fallback) | |
132 | 130 | | :--- | :--- | :--- | :--- | |
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` | |
134 | 133 | | **Return Values** | `@phpstan-return` | `@psalm-return` | `@return` | |
135 | 134 |
|
136 | 135 | --- |
@@ -168,11 +167,11 @@ registerUser(age: 25, username: 'Alice', id: -5); |
168 | 167 |
|
169 | 168 | TypePHP natively supports PHP's by-reference parameter semantics (`function update(int &$value)`). |
170 | 169 |
|
171 | | -### How By-Reference Validation Works |
| 170 | +### How By-Reference Input Validation Works (`@param`) |
172 | 171 |
|
173 | 172 | 1. **Entry Guard Rails:** TypePHP inspects and validates the variable's value *on function entry* before the function body executes. |
174 | 173 | 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**. |
176 | 175 |
|
177 | 176 | ```php |
178 | 177 | <?php |
@@ -227,88 +226,73 @@ function incrementCount(int &$count): void { $count++; } |
227 | 226 | function incrementCount(int &$count): void { $count++; } |
228 | 227 | ``` |
229 | 228 |
|
230 | | -### By-Reference Arrays & Shapes |
| 229 | +--- |
| 230 | + |
| 231 | +## By-Reference Out-Parameter Contracts (`@param-out`) |
231 | 232 |
|
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. |
233 | 236 |
|
234 | 237 | ```php |
235 | 238 | /** |
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 |
237 | 244 | */ |
238 | | -function appendReward(array &$scores): void |
| 245 | +function initializeIdentifier(mixed &$value): void |
239 | 246 | { |
240 | | - $scores[] = 500; // Mutates array in caller scope |
| 247 | + $value = 42; // Valid mutation |
241 | 248 | } |
242 | 249 |
|
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 |
248 | 253 |
|
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 |
254 | 254 | /** |
255 | | - * @param positive-int &...$numbers |
| 255 | + * Failing Out-Parameter Example |
| 256 | + * |
| 257 | + * @param mixed &$value |
| 258 | + * @param-out positive-int $value |
256 | 259 | */ |
257 | | -function doubleAll(int &...$numbers): void |
| 260 | +function badInitialize(mixed &$value): void |
258 | 261 | { |
259 | | - foreach ($numbers as &$num) { |
260 | | - $num *= 2; |
261 | | - } |
| 262 | + $value = -50; // Invalid: Violates positive-int! |
262 | 263 | } |
263 | 264 |
|
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 |
271 | 268 | ``` |
272 | 269 |
|
273 | | -### OOP & Interface Inheritance for By-Reference Parameters |
| 270 | +### Full Type Algebra Support in `@param-out` |
274 | 271 |
|
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` |
276 | 277 |
|
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 |
286 | 279 |
|
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`: |
300 | 281 |
|
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 | +]; |
305 | 289 | ``` |
306 | 290 |
|
307 | 291 | --- |
308 | 292 |
|
309 | 293 | ## Class Methods (Instance & Static) |
310 | 294 |
|
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**: |
312 | 296 |
|
313 | 297 | ```php |
314 | 298 | class UserService |
|
0 commit comments