-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample.php
More file actions
4783 lines (3866 loc) · 173 KB
/
example.php
File metadata and controls
4783 lines (3866 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* PHP Showcase
*
* A single-file playground for every completion, go-to-definition, and
* go-to-type-definition feature. Trigger completion after -> / :: / $,
* Ctrl+Click for go-to-definition, or use "Go to Type Definition" to
* jump to the class declaration of a variable's resolved type.
*
* Layout:
* 1. DEMOS — open any demo() method and try completion inside it
* 2. SCAFFOLDING — supporting definitions (scroll past these)
*
* Priority:
* Basic everyday features → Laravel → Trivial (works everywhere) → Advanced
*/
namespace Demo {
use Exception;
use Stringable;
use Demo\UserProfile as Profile;
// ═══════════════════════════════════════════════════════════════════════════
// DEMOS — open any demo() method and trigger completion inside
// ═══════════════════════════════════════════════════════════════════════════
// ── Auto-Import (completion) ────────────────────────────────────────────────
// Try: type `new DateT` and accept `DateTime`. The `use DateTime;` statement
// is inserted between `use Exception;` and `use Stringable;` above to
// maintain alphabetical order.
//
// The `use Exception;` import above occupies the short name "Exception".
// Try: type `throw new pq\Exception()` and accept — the auto-import inserts
// `\pq\Exception` at the usage site instead of a conflicting `use` statement.
// ── Namespace Segment Completion ────────────────────────────────────────────
// Try: erase the class name after `use Demo\` and trigger completion to see
// namespace segments (module/folder icon) alongside class names.
// ── Namespaced Function Completion ──────────────────────────────────────────
// Try: type `use function parse_file` and accept to get
// `use function ast\parse_file;`
// ── Instance Completion ─────────────────────────────────────────────────────
class InstanceCompletionDemo
{
public function demo(): void
{
$zoo = new Zoo();
$zoo->aardvark(); // own method
$zoo->baboon; // own property
$zoo->buffalo; // constructor-promoted property
$zoo->cheetah; // readonly promoted (from base)
$zoo->dingo(); // trait method
$zoo->elephant('Hi'); // trait method
$zoo->falcon(); // inherited from parent
$zoo->gorilla; // @property (own class)
$zoo->hyena('x'); // @method (own class)
$zoo->iguana; // @property-read (interface)
$zoo->jaguar(); // @method (interface)
// MUST NOT appear: $keeper (protected), $ceo (private), nocturnal() (private)
}
}
// ── Mixed Accessor Chaining ─────────────────────────────────────────────────
class MixedAccessorDemo
{
public function demo(): void
{
$foobar = new StaticPropHolder();
$foobar->holder::$shared; // $obj->prop::$static chain
// Inline (new Foo)->method() chaining
(new Pen())->write(); // resolves Pen then write()
}
}
// ── Method & Property Chaining ──────────────────────────────────────────────
class ChainingDemo
{
public function demo(): void
{
$studio = new ScaffoldingChainingDemo();
// Fluent method chains — MUST NOT appear: calibrate() (protected)
$studio->brush->setSize('large')->setStyle('pointed')->stroke();
// Return type chains
$studio->brush->getCanvas()->title();
// Variable → method chain
$canvas = $studio->brush->getCanvas();
$canvas->getBrush()->stroke();
// Deep property chain
$studio->canvas->easel->material;
$studio->canvas->easel->height();
// Null-safe chaining
$maybe = Brush::find(1);
$maybe?->getCanvas()?->title();
// Multi-line method chains
$studio->brush->setSize('large')
->setStyle('pointed')
->stroke();
// Variable assigned from chain
$directBrush = $studio->brush->getCanvas()->getBrush();
$directBrush->stroke();
// (new Class())->method()
$fromNew = (new Canvas())->getBrush();
$fromNew->stroke();
// Intermediate variable from property access
$easel = (new Canvas())->easel;
$easel->material;
}
}
// ── @var Docblock Override ──────────────────────────────────────────────────
class VarDocblockDemo
{
public function demo(): void
{
/** @var Pencil $inlineHinted */
$inlineHinted = getUnknownValue();
$inlineHinted->sketch(); // with explicit variable name
/** @var Pen */
$hinted = getUnknownValue();
$hinted->write(); // without variable name (PHPStorm fails this)
}
}
// ── Return Type Resolution ──────────────────────────────────────────────────
class ReturnTypeDemo
{
public function demo(): void
{
$made = Pen::make(); // static return type → Pen
$made->write();
$marker = Marker::make(); // static on subclass → Marker
$marker->highlight(); // resolves to Marker, not Pen
$fluent = $marker->rename('Bold'); // rename returns static → Marker
$fluent->highlight(); // chained static stays on the subclass
$created = makePen();
$created->write(); // function return type
// MUST NOT appear: refill() (private)
$found = pickPenOrPencil(); // Pen|Pencil union
$found->label(); // available on both types
}
}
// ── Type Narrowing ──────────────────────────────────────────────────────────
class TypeNarrowingDemo
{
public function demo(): void
{
$specimen = pickRockOrBanana(); // Rock|Banana
if ($specimen instanceof Rock) {
$specimen->crush(); // narrowed to Rock
// MUST NOT appear: peel() (Banana only)
} else {
$specimen->peel(); // narrowed to Banana (else branch)
// MUST NOT appear: crush() (Rock only)
}
if (!$specimen instanceof Rock) {
$specimen->peel(); // negated instanceof
}
$unknown = getUnknownValue();
if (is_a($unknown, Rock::class)) {
$unknown->crush(); // is_a() narrowing
}
$target = getUnknownValue();
assert($target instanceof Banana);
$target->peel(); // assert() narrowing
// Inline && narrowing — RHS of && sees the narrowed type from LHS
$sample = pickRockOrBanana();
if ($sample instanceof Rock && $sample->crush()) {
// $sample is Rock here too
}
}
}
// ── Custom Assert Narrowing ─────────────────────────────────────────────────
class AssertNarrowingDemo
{
public function demo(): void
{
$unknown = getUnknownValue();
assertRock($unknown); // @phpstan-assert Rock $value
$unknown->crush();
$sample = pickRockOrBanana();
if (isRock($sample)) { // @phpstan-assert-if-true Rock
$sample->crush();
} else {
$sample->peel();
}
$maybe = pickRockOrBanana();
if (isNotRock($maybe)) { // @phpstan-assert-if-false Rock
$maybe->peel();
} else {
$maybe->crush();
}
}
}
// ── Static Method Assert Narrowing ─────────────────────────────────────────
class StaticAssertNarrowingDemo
{
public function demo(): void
{
// @phpstan-assert on static method — unconditional narrowing
$unknown = getUnknownValue();
StaticAssert::assertRock($unknown);
$unknown->crush(); // narrowed to Rock
// @phpstan-assert-if-true on static method — narrows in then-branch
$sample = pickRockOrBanana();
if (StaticAssert::isRock($sample)) {
$sample->crush(); // narrowed to Rock
}
// @phpstan-assert-if-false on static method — narrows in else-branch
$maybe = pickRockOrBanana();
if (StaticAssert::isNotRock($maybe)) {
$maybe->peel(); // narrowed to Banana
} else {
$maybe->crush(); // narrowed to Rock
}
}
}
// ── Guard Clause Narrowing (Early Return / Throw) ──────────────────────────
class GuardClauseDemo
{
public function demo(): void
{
$subject = pickRockOrBanana(); // Rock|Banana
if (!$subject instanceof Banana) {
return; // early return — guard clause
}
$subject->peel(); // narrowed to Banana after guard
$candidate = pickRockOrBanana(); // Rock|Banana
if ($candidate instanceof Rock) {
throw new Exception('no rocks'); // early throw — guard clause
}
$candidate->peel(); // narrowed to Banana (Rock excluded)
$unknown = getUnknownValue();
if (!$unknown instanceof Rock) return; // single-statement guard (no braces)
$unknown->crush(); // narrowed to Rock
}
}
// ── in_array Strict-Mode Narrowing ─────────────────────────────────────────
class InArrayNarrowingDemo
{
/**
* @param Rock|Banana $item
* @param list<Rock> $rocks
*/
public function demo($item, array $rocks): void
{
if (in_array($item, $rocks, true)) {
$item->crush(); // narrowed to Rock
// MUST NOT appear: peel() (Banana only)
} else {
$item->peel(); // excluded Rock → Banana
// MUST NOT appear: crush() (Rock only)
}
// Guard clause with in_array
$specimen = pickRockOrBanana(); // Rock|Banana
if (!in_array($specimen, $rocks, true)) {
return;
}
$specimen->crush(); // narrowed to Rock after guard
}
}
// ── Generics (@template / @extends) ────────────────────────────────────────
class GenericsDemo
{
public function demo(): void
{
$repo = new PenRepository();
$repo->find(1)->write(); // Repository<Pen>::find() → Pen
$repo->findOrNull(1)?->write(); // ?Pen
$pens = new PenCollection(); // TypedCollection<int, Pen>
$pens->first()->write();
// MUST NOT appear: refill() (private on Pen)
$pens->thickOnly(); // own method on subclass
$cachingRepo = new CachingPenRepository();
$cachingRepo->find(1)->write(); // grandparent generics
$responses = new ResponseCollection(); // @phpstan-extends variant
$responses->first()->getStatusCode();
}
}
// ── @implements Generic Resolution ─────────────────────────────────────────
class ImplementsGenericDemo
{
public function demo(): void
{
$repo = new PenStorage();
$repo->find(1)->write(); // @implements Storage<Pen> → Pen
$penCatalog = new PenCatalog();
$penCatalog->find(1)->write(); // @template-implements alias
$items = new ItemIterableCollection();
foreach ($items as $item) {
$item->write(); // @implements IteratorAggregate<Pen>
}
}
}
// ── Conditional Return Types ────────────────────────────────────────────────
class ConditionalReturnDemo
{
public function demo(): void
{
$container = new Container();
$resolved = $container->make(Pen::class);
$resolved->write(); // class-string<T> → T
$appPen = app(Pen::class); // conditional on standalone function
$appPen->write();
// Literal string conditional return type
$mapper = new TreeMapperImpl();
$result = $mapper->map('foo', 'bar');
$result->write(); // "foo" → Pen (literal string match)
}
}
// ── Method-Level @template ──────────────────────────────────────────────────
class MethodTemplateDemo
{
public function demo(): void
{
$locator = new ServiceLocator();
$locator->get(Pen::class)->write(); // class-string<T> → T
Factory::create(Pen::class)->write(); // static @template
resolve(Marker::class)->highlight(); // function @template
$mapper = new ObjectMapper();
$mapped = $mapper->wrap(new Pen());
$mapped->first(); // → Pen (T resolved from argument)
$mapper->wrap(new Product())->first()->getPrice(); // new expression arg → Product
// Variadic class-string<T> → union return type
$locator2 = new ServiceLocator();
$union = $locator2->getAny(Pen::class, Marker::class);
$union->write(); // A|B from variadic class-string<T>
$union->highlight();
// Nested generic return: @return Box<T> with class-string<T> param
$boxed = $locator->wrap(Pen::class);
$boxed->unwrap()->write(); // Box<T>::unwrap() → Pen
}
}
// ── Trait Generic Substitution ──────────────────────────────────────────────
class TraitGenericDemo
{
public function demo(): void
{
Product::factory()->create(); // @use HasFactory<UserFactory> → UserFactory
Product::factory()->count(5)->make(); // count() returns static, make() returns Product
$idx = new PenIndex(); // @use Indexable<int, Pen>
$idx->get()->write(); // TValue → Pen
}
}
// ── Foreach & Array Access ──────────────────────────────────────────────────
class ForeachArrayAccessDemo
{
public function demo(): void
{
/** @var list<Pen> $members */
$members = getUnknownValue();
foreach ($members as $member) {
$member->write(); // element type from list<Pen>
}
$members[0]->color(); // array access element type
/** @var array<int, Pen> */
$annotated = []; // @var without variable name
$annotated[0]->write(); // type from next-line annotation
$inferred = [new Pen(), new Marker()];
$inferred[0]->write(); // element type inferred from literal
}
}
// ── Array Destructuring ────────────────────────────────────────────────────
class ArrayDestructuringDemo
{
public function demo(): void
{
/** @var list<Pen> */
[$first, $second] = getUnknownValue();
$first->write(); // destructured element type
}
}
// ── Array Shapes ────────────────────────────────────────────────────────────
class ArrayShapeDemo
{
public function demo(): void
{
// Literal array shape — key completion and value types
$config = ['host' => 'localhost', 'port' => 3306, 'tool' => new Pen()];
$config['']; // Try: key completion: host, port, tool
$config['tool']->write(); // value type → Pen
// Annotated shape
/** @var array{first: Pen, second: Pencil} $pair */
$pair = getUnknownValue();
$pair['first']->write();
$pair['second']->sketch();
// Shape from function return type
$cfg = getAppConfig();
$cfg['logger']->write();
}
}
// ── Object Shapes ───────────────────────────────────────────────────────────
class ObjectShapeDemo
{
public function demo(): void
{
/** @var object{title: string, score: float} $item */
$item = getUnknownValue();
$item->title; // Ctrl+Click → jumps to `title:` in docblock above
$item->score; // Ctrl+Click → jumps to `score:` in docblock above
}
}
// ── Spread Operator Type Tracking ───────────────────────────────────────────
class SpreadOperatorDemo
{
public function demo(): void
{
/** @var list<Pen> */
$penList = [];
/** @var list<Pencil> */
$pencilList = [];
$allPens = [...$penList];
$allPens[0]->write(); // resolves Pen from spread
$everything = [...$penList, ...$pencilList];
$everything[0]->label(); // union: Pen|Pencil from multiple spreads
}
}
// ── Clone Expression ────────────────────────────────────────────────────────
class CloneDemo
{
public function demo(): void
{
$pen = new Pen('blue');
$copy = clone $pen;
$copy->write(); // preserves Pen type
}
}
// ── Class-String Variable Static Access ─────────────────────────────────────
class ClassStringStaticDemo
{
public function demo(): void
{
$cls = Pen::class;
$cls::make(); // static method from Pen
}
}
// ── Ambiguous Variables ─────────────────────────────────────────────────────
class AmbiguousVariableDemo
{
public function demo(): void
{
if (rand(0, 1)) {
$ambiguous = new Lamp();
} else {
$ambiguous = new Faucet();
}
$ambiguous->turnOff(); // available on both branches
$ambiguous->dim(); // available on Lamp branches
$ambiguous->drip(); // available on Faucet branches
}
}
// ── Parenthesized Assignment ────────────────────────────────────────────────
class ParenthesizedAssignmentDemo
{
public function demo(): void
{
$parenPen = (new Pen('red'));
$parenPen->write(); // resolves through parentheses
}
}
// ── String Interpolation ────────────────────────────────────────────────────
class StringInterpolationDemo
{
public function demo(): void
{
$pen = new Pen('blue');
echo "Ink is {$pen->color()}"; // brace interpolation — full completion
echo "Tool: $pen->ink"; // simple interpolation
echo 'no $pen-> here'; // single-quoted — suppressed
}
}
// ── Foreach over Generic Collection Classes ─────────────────────────────────
class CollectionForeachDemo
{
public function demo(): void
{
$src = new ScaffoldingCollectionForeach();
// From method return type
foreach ($src->allMembers() as $user) {
$user->getName(); // via method return type → collection generics
}
// From new instance
$items = new UserEloquentCollection();
foreach ($items as $item) {
$item->getEmail(); // resolves to User via @extends generics
}
// From property type
foreach ($src->members as $user) {
$user->getEmail(); // via property type → collection generics
}
// From variable
$collection = $src->allMembers();
foreach ($collection as $user) {
$user->getName(); // via variable assignment scanning
}
}
}
// ── Type Aliases (@phpstan-type / @phpstan-import-type) ─────────────────────
/**
* @phpstan-type UserData array{name: string, email: string, pen: Pen}
* @phpstan-type StatusInfo array{code: int, label: string, owner: User}
* @phpstan-type UserList array<int, Profile>
*/
class TypeAliasDemo
{
public function demo(): void
{
$data = $this->getUserData();
$data['name']; // @phpstan-type → array shape key completion
$data['pen']->write(); // object value → method completion
$status = $this->getStatus();
$status['label']; // StatusInfo alias → array shape keys
$status['owner']->getEmail(); // object value → method completion
// Type alias resolves through foreach iteration
foreach ($this->getUsers() as $user) {
$user->getDisplayName(); // UserList → array<int, Profile> → Profile
}
}
/** @return UserData */
public function getUserData(): array
{
return ['name' => 'Alice', 'email' => 'alice@example.com', 'pen' => new Pen()];
}
/** @return StatusInfo */
public function getStatus(): array
{
return ['code' => 200, 'label' => 'OK', 'owner' => new User('Alice', 'alice@example.com')];
}
/** @return UserList */
public function getUsers(): array
{
return [];
}
}
/**
* @phpstan-import-type UserData from TypeAliasDemo
* @phpstan-import-type StatusInfo from TypeAliasDemo as AliasedStatus
*/
class TypeAliasImportDemo
{
public function demo(): void
{
$user = $this->fetchUser();
$user['email']; // imported UserData → array shape keys
$user['pen']->color(); // object value → method completion
$status = $this->fetchStatus();
$status['code']; // AliasedStatus → StatusInfo → array shape keys
$status['owner']->getName(); // object value → method completion
}
/** @return UserData */
public function fetchUser(): array
{
return ['name' => 'Bob', 'email' => 'bob@example.com', 'pen' => new Pen()];
}
/** @return AliasedStatus */
public function fetchStatus(): array
{
return ['code' => 404, 'label' => 'Not Found', 'owner' => new User('Bob', 'bob@example.com')];
}
}
// ── Multi-line @return & Broken Docblock Recovery ───────────────────────────
class BrokenDocblockDemo
{
public function demo(): void
{
$collection = collect([]);
$collection->groupBy('key'); // multi-line @return resolves correctly
$recovered = (new BrokenDocRecovery())->broken();
$recovered->working(); // recovers `static` from broken @return static<
}
}
// ── Callable / Closure Variable Invocation ──────────────────────────────────
class ClosureInvocationDemo
{
public function demo(): void
{
// Closure literal with native return type hint
$makePen = function(): Pen { return new Pen(); };
$makePen()->write(); // resolves Pen from closure return type
// Arrow function literal
$makePencil = fn(): Pencil => new Pencil();
$makePencil()->sketch(); // arrow fn return type
// Docblock callable annotation
/** @var \Closure(): Pencil $supplier */
$supplier = getUnknownValue();
$supplier()->sharpen(); // @var Closure() annotation
// Chaining after callable invocation
$builder = function(): Pen { return new Pen(); };
$builder()->rename('Bold')->write(); // chain after $fn()
// Variable assigned from callable invocation
$fromClosure = $makePen();
$fromClosure->write(); // $result = $fn() resolves return type
// Immediately invoked arrow function with return type
$result = (fn(): Pen => new Pen())();
$result->write(); // resolves Pen from arrow fn return type
// Immediately invoked closure with return type
$obj = (function(): Pencil { return new Pencil(); })();
$obj->sketch(); // resolves Pencil from closure return type
}
}
// ── class-string Variable Resolution ────────────────────────────────────────
class ClassStringVarDemo
{
public function demo(): void
{
// new $var where $var holds a class-string
$cls = Pen::class;
$pen = new $cls;
$pen->write(); // resolves Pen from class-string
// $var::staticMethod() where $var holds a class-string
$userClass = User::class;
$found = $userClass::findByEmail('test@example.com');
$found->getEmail(); // resolves User from class-string static call
}
}
// ── iterator_to_array Resolution ────────────────────────────────────────────
class IteratorToArrayDemo
{
public function demo(): void
{
/** @var \Iterator<int, Pen> $iter */
$iter = getUnknownValue();
$items = iterator_to_array($iter);
$items[0]->write(); // resolves Pen from iterator value type
}
}
// ── Compound Negated Guard Clause Narrowing ─────────────────────────────────
class CompoundNegatedNarrowingDemo
{
/** @param Rock|Banana|Lamp $thing */
public function demo($thing): void
{
// After both negated instanceof checks exit, $thing is Rock|Banana
if (!$thing instanceof Rock && !$thing instanceof Banana) {
return;
}
$thing->weigh(); // both Rock and Banana have weigh()
}
}
// ── __invoke() Return Type Resolution ───────────────────────────────────────
class InvokeReturnTypeDemo
{
public function demo(): void
{
// Objects with __invoke() can be called like functions.
// PHPantom resolves the return type through __invoke().
$formatter = new ScaffoldingFormatter();
$formatter()->write(); // __invoke() returns Pen
// Chaining through __invoke() return type
$factory = new ScaffoldingPenFactory();
$factory()->rename('Fine')->write(); // __invoke() → Pen → rename() → Pen
// Parenthesized property invocation: ($this->prop)()
($this->formatter)()->write(); // resolves through __invoke()
// Foreach over __invoke() return type with docblock
$fetcher = new ScaffoldingPenFetcher();
foreach ($fetcher() as $item) {
$item->write(); // @return Pen[] on __invoke()
}
// Enum from()/tryFrom() chains to instance methods
Status::from('Active')->label(); // from() returns Status
}
private ScaffoldingFormatter $formatter;
}
// ── Anonymous Classes ───────────────────────────────────────────────────────
class AnonymousClassDemo
{
public function demo(): object
{
return new class extends Pen {
public string $brand;
public function cap(): string { return ''; }
public function demo() {
$this->cap(); // own method
$this->brand; // own property
$this->write(); // inherited from Pen
// MUST NOT appear: refill() (private — not inherited)
}
};
}
}
// ── Match / Ternary / Null-Coalescing Type Accumulation ─────────────────────
class ExpressionTypeDemo
{
public function demo(): void
{
$src = new ScaffoldingExpressionType();
// Null-coalescing
$fallback = $src->backup ?? $src->primary;
$fallback->getStatusCode(); // Response method
// Match expression — shared members sort above branch-only members
$service = match (rand(0, 1)) {
0 => new ElasticProductReviewIndexService(),
1 => new ElasticBrandIndexService(),
};
$service->index(); // on both — sorted first
$service->reindex(); // one branch only — sorted after
// Ternary
$svc = rand(0, 1)
? new ElasticProductReviewIndexService()
: new ElasticBrandIndexService();
$svc->index(); // on both — sorted first
}
}
// ── Switch Statement Type Tracking ──────────────────────────────────────────
class SwitchDemo
{
public function demo(string $type): void
{
switch ($type) {
case 'reviews':
$service = new ElasticProductReviewIndexService();
break;
case 'brands':
$service = new ElasticBrandIndexService();
break;
}
$service->index(); // on both classes
}
}
// ── Array & Object Shapes in Methods ────────────────────────────────────────
class ShapeMethodDemo
{
public function demo(): void
{
$data = $this->getToolKit();
$data['pen']->write(); // Pen
$data['pencil']->sketch(); // Pencil
// Nested annotated shape
/** @var array{meta: array{page: int, total: int}, items: list<Pen>} $response */
$response = getUnknownValue();
$response['meta']['page']; // nested shape key
$response['items'][0]->write(); // list element type
// Nested keys inferred from literal — no annotation needed
$config = ['db' => ['host' => 'localhost', 'port' => 3306], 'debug' => true];
$config['db']['host']; // Try: delete 'host' and trigger completion
// Object shapes
$profile = $this->getProfile();
$profile->name; // Ctrl+Click → jumps to `name:` in @return docblock
$result = $this->getResult();
$result->tool->write(); // Ctrl+Click `tool` → jumps to `tool:` in @return docblock
$result->meta->page; // Ctrl+Click `meta` → jumps to `meta:` in @return docblock
}
/** @return array{pen: Pen, pencil: Pencil, active: bool} */
public function getToolKit(): array { return []; }
/** @return object{name: string, age: int, active: bool} */
public function getProfile(): object { return (object) []; }
/** @return object{tool: Pen, meta: object{page: int, total: int}} */
public function getResult(): object { return (object) []; }
/** @param array{host: string, port: int, tool: Pen} $config */
public function fromParam(array $config): void
{
$config['host']; // string
$config['tool']->write(); // Pen
}
}
// ── Named Key Destructuring from Array Shapes ───────────────────────────────
class DestructuringShapeDemo
{
public function demo(): void
{
// Named key from method return
['pen' => $pen, 'pencil' => $pencil] = $this->getToolKit();
$pen->write(); // Pen from 'pen' key
$pencil->sketch(); // Pencil from 'pencil' key
// Named key from @var annotated variable
/** @var array{pen: Pen, pencil: Pencil, active: bool} $data */
$data = getUnknownValue();
['pen' => $myPen, 'pencil' => $myPencil] = $data;
$myPen->write(); // Pen from 'pen' key
$myPencil->sketch(); // Pencil from 'pencil' key
// Positional from shape
/** @var array{Pen, Pencil} $pair */
$pair = getUnknownValue();
[$first, $second] = $pair;
$first->write(); // Pen (positional index 0)
$second->sketch(); // Pencil (positional index 1)
// list() syntax
/** @var array{recipe: Recipe, servings: int} $meal */
$meal = getUnknownValue();
list('recipe' => $recipe) = $meal;
$recipe->ingredients; // Recipe from 'recipe' key
}
/** @return array{pen: Pen, pencil: Pencil, count: int} */
public function getToolKit(): array { return []; }
}
// ── Generic Context Preservation ────────────────────────────────────────────
class GenericContextDemo
{
public function demo(): void
{
$src = new ScaffoldingGenericContext();
$src->chest->unwrap()->open(); // Box<Gift>::unwrap() → Gift
$src->display()->first()->open(); // TypedCollection<int, Gift>::first() → Gift
}
}