Skip to content

Commit 2b7702b

Browse files
committed
Enhance documentation on deep and boundary enforcement for generics in TypePHP
1 parent ee871a9 commit 2b7702b

1 file changed

Lines changed: 73 additions & 12 deletions

File tree

‎docs/generics/basics-and-bounds.md‎

Lines changed: 73 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,68 @@ TypePHP manages generic templates at two distinct execution levels:
3838

3939
---
4040

41+
## Deep Enforcement vs. Boundary Enforcement (Included vs. Excluded Classes)
42+
43+
It is crucial to understand **when** TypePHP intercepts a generic type violation. This depends entirely on whether the generic class (e.g., `Collection`) is **included** or **excluded** in your `typephp.php` configuration.
44+
45+
### 1. Included Classes (Deep Enforcement)
46+
If you want TypePHP to throw an error the exact millisecond you call an internal method like `$collection->add(new Product())` or `new Collection([1, 'invalid'])`, **the generic class itself must be whitelisted in your `typephp.php` `include` array.**
47+
48+
When a class is included, TypePHP intercepts every method call and constructor inside it.
49+
50+
```php
51+
// 1. You explicitly included your custom collection:
52+
// 'include' => ['app/Support/MyCollection.php']
53+
54+
/** @var MyCollection<int, User> $users */
55+
$users = new MyCollection();
56+
57+
// Throws TypeError IMMEDIATELY inside MyCollection::add()
58+
// "Argument $item (template TValue) must be of type User, Product given"
59+
$users->add(new Product());
60+
```
61+
62+
### 2. Excluded Classes (Boundary Enforcement)
63+
Most third-party generic containers (like Laravel's `Illuminate\Support\Collection` or Doctrine's `ArrayCollection`) live in `vendor/**`, which is usually **excluded** for maximum framework performance.
64+
65+
When a generic class is excluded, TypePHP **does not intercept its internal constructors or methods, and does not inspect its internal properties**. Instead, it tracks the object's generic "badge" in memory and strictly enforces the contract **by comparing badges** when the object crosses into an included function or method.
66+
67+
```php
68+
// 1. Laravel Collections are excluded:
69+
// 'exclude' => ['vendor/**']
70+
71+
// 2. You label the collection in your app/ code:
72+
/** @var Illuminate\Support\Collection<int, string> $strings */
73+
$strings = new Collection(['valid_string', 12345]);
74+
75+
// NO ERROR THROWN YET!
76+
// Because Collection.php is excluded, TypePHP does not intercept the constructor
77+
// to check the raw array contents. It simply attaches the `string` badge to the object.
78+
79+
// 3. BOUNDARY GATEKEEPER CATCHES TYPE CONFLICTS
80+
class NumberService {
81+
/** @param Collection<int, int> $numbers */
82+
public function process(Collection $numbers) {}
83+
}
84+
85+
$service = new NumberService();
86+
87+
// 💥 Throws TypeError at the function boundary!
88+
// "Argument $numbers expects Collection<covariant int>, but Collection<string> was given"
89+
$service->process($strings);
90+
```
91+
92+
**Why this happens:** TypePHP doesn't open the sealed "Vendor Box" to look at the `12345` or `'valid_string'` inside it. Instead, the `NumberService` acts as a gatekeeper:
93+
* *"I require a box labeled `int`."*
94+
* *"You handed me a box labeled `string`."*
95+
* **Access Denied.**
96+
97+
### Which should you choose?
98+
* **Exclude generic framework classes (`vendor/**`)** to keep the framework booting at 100% native C-speed. TypePHP will still perfectly guard your application code (`app/**`) by ensuring no generic containers with conflicting type badges ever cross into your services or controllers.
99+
* **Include specific generic classes** if you own them (e.g. `app/Data/Result.php`), or if you specifically want deep, immediate validation on every single method call and constructor argument within that container.
100+
101+
---
102+
41103
## PHP Limitation: No Native `instanceof` on Generics
42104

43105
In PHP, writing generic syntax directly in executable statements (such as `if ($obj instanceof Collection<User>)`) is a syntax error.
@@ -192,35 +254,35 @@ Generic parameters (`T`) in TypePHP are not limited to object classes. You can b
192254
### Generic Collections of Refined Scalars (`Collection<positive-int>`)
193255

194256
```php
195-
/** @var Collection<positive-int> $scores */
196-
$scores = new Collection();
257+
/** @var MyCollection<positive-int> $scores */
258+
$scores = new MyCollection();
197259

198260
$scores->add(100); // Valid
199261

200262
$scores->add(-50);
201-
// Throws: TypeError: Collection::add(): Argument $item (template T = positive-int) must be of type positive-int
263+
// Throws: TypeError: MyCollection::add(): Argument $item (template T = positive-int) must be of type positive-int
202264
```
203265

204266
### Generic Collections of Array Shapes (`Collection<array{...}>`)
205267

206268
```php
207-
/** @var Collection<array{id: positive-int, name: non-empty-string}> $userShapes */
208-
$userShapes = new Collection();
269+
/** @var MyCollection<array{id: positive-int, name: non-empty-string}> $userShapes */
270+
$userShapes = new MyCollection();
209271

210272
$userShapes->add(['id' => 1, 'name' => 'Alice']); // Valid
211273

212274
$userShapes->add(['id' => -5, 'name' => 'Alice']);
213-
// Throws: TypeError: Collection::add(): Argument $item['id'] must be of type positive-int
275+
// Throws: TypeError: MyCollection::add(): Argument $item['id'] must be of type positive-int
214276
```
215277

216278
---
217279

218280
## First-Use Type Inference (Unannotated Generic Instances)
219281

220-
If you instantiate a generic class without an inline `@var` prebinding annotation:
282+
If you instantiate an **included** generic class without an inline `@var` prebinding annotation:
221283

222284
```php
223-
$collection = new Collection(); // No @var Collection<User> annotation!
285+
$collection = new MyCollection(); // No @var MyCollection<User> annotation!
224286
```
225287

226288
TypePHP automatically infers the template parameter `T` from the **first method call** executed on that object instance and locks `T` to that type in `WeakMap` memory for all subsequent calls:
@@ -234,14 +296,14 @@ $collection->add(new User('Bob'));
234296

235297
// 3. Subsequent call fails because T was locked to User on first use!
236298
$collection->add(new Product('SKU-100'));
237-
// Throws: TypeError: Collection::add(): Argument $item (template T = User) must be of type User, Product given
299+
// Throws: TypeError: MyCollection::add(): Argument $item (template T = User) must be of type User, Product given
238300
```
239301

240302
---
241303

242304
## Simultaneous First-Use Multi-Template Inference
243305

244-
If you instantiate a multi-template class without an inline `@var` annotation:
306+
If you instantiate an **included** multi-template class without an inline `@var` annotation:
245307

246308
```php
247309
/**
@@ -282,5 +344,4 @@ $bag->set(12345, 30);
282344
// 4. Subsequent call violating locked V = int fails
283345
$bag->set('timeout', 'thirty');
284346
// Throws: TypeError: MultiTemplateBag::set(): Argument $val (template V = int) must be of type int
285-
```
286-
347+
```

0 commit comments

Comments
 (0)