Repository navigation
Expand file tree
/
Copy pathcompletion.php
More file actions
5841 lines (4830 loc) · 235 KB
/
Copy pathcompletion.php
File metadata and controls
5841 lines (4830 loc) · 235 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 — Completion
*
* Completion and the type inference behind it: chaining, narrowing,
* generics, docblock tags, arrays and shapes, closures, generators, and
* everything else that decides what the member list after `->` or `::`
* should contain. Open any demo() method and trigger completion inside.
*
* One of the demo files listed in README.md. Supporting fixtures live in
* scaffolding/scaffolding.php (namespace Demo\Scaffolding), and the runtime
* assertions that verify the type claims in the comments below live in
* scaffolding/assertions.php.
*/
namespace Demo;
use Demo\Scaffolding;
use Demo\Scaffolding\UserProfile as Profile;
use Exception;
// ═══════════════════════════════════════════════════════════════════════════
// 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 at the top of the import list above to maintain alphabetical
// order (it sorts ahead of the `Demo\Scaffolding\...` imports).
//
// 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 Scaffolding\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 Scaffolding\StaticPropHolder();
$foobar->holder::$shared; // $obj->prop::$static chain
// Inline (new Foo)->method() chaining
(new Scaffolding\Pen())->write(); // resolves Scaffolding\Pen then write()
}
}
// ── Pseudo-Type Class-Name Collision ────────────────────────────────────────
// A class may be named after a PHPDoc pseudo-type such as `number` (PHP 8.4
// ships `BcMath\Number`). The class must not be shadowed by the pseudo-type.
class PseudoTypeCollisionDemo
{
public function demo(): void
{
$n = new Scaffolding\Number('42');
$n->value; // own property resolves (not treated as int|float)
$n->scaled(2); // own method resolves
// A `Scaffolding\Number` parameter type resolves to the class, so passing a
// `Scaffolding\Number` instance is accepted (no false type-mismatch diagnostic).
Scaffolding\scaleNumber($n);
}
}
// ── Method & Property Chaining ──────────────────────────────────────────────
class ChainingDemo
{
public function demo(): void
{
$studio = new Scaffolding\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 = Scaffolding\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 Scaffolding\Canvas())->getBrush();
$fromNew->stroke();
// Intermediate variable from property access
$easel = (new Scaffolding\Canvas())->easel;
$easel->material;
}
}
// ── Trait `return $this` Fluent Chains ──────────────────────────────────────
// A trait method whose body is `return $this;` (no declared return type)
// resolves to the class that uses the trait, so a chained call continues with
// the using class's own members — not just the trait's.
class TraitFluentChainDemo
{
public function demo(): void
{
$page = new Scaffolding\TestablePage();
// Each step resolves to Scaffolding\TestablePage (the using class), so the whole
// chain — including Scaffolding\TestablePage's own members — stays available.
$page->assertSee('Welcome') // trait method, body `return $this;`
->assertSee('Dashboard') // still Scaffolding\TestablePage, not the trait
->status; // using class's own property
$page->assertSee('x')->refresh(); // using class's own method resolves
}
}
// ── @var Docblock Override ──────────────────────────────────────────────────
class VarDocblockDemo
{
public function demo(): void
{
/** @var Scaffolding\Pencil $inlineHinted */
$inlineHinted = Scaffolding\getUnknownValue();
$inlineHinted->sketch();
/** @var Scaffolding\Pen */
$hinted = Scaffolding\getUnknownValue();
$hinted->write(); // without variable name (PHPStorm fails this)
}
}
// ── Return Type Resolution ──────────────────────────────────────────────────
class ReturnTypeDemo
{
public function demo(): void
{
$made = Scaffolding\Pen::make(); // static return type → Scaffolding\Pen
$made->write();
$marker = Scaffolding\Marker::make(); // static on subclass → Scaffolding\Marker
$marker->highlight(); // resolves to Scaffolding\Marker, not Scaffolding\Pen
$fluent = $marker->rename('Bold'); // rename returns static → Scaffolding\Marker
$fluent->highlight(); // chained static stays on the subclass
// Writing the class out pins it: `static` here can only ever be
// `Scaffolding\Marker`, so hover reads `Scaffolding\Marker` and not `static(Scaffolding\Marker)`. A
// forwarding call is the case that stays open — see
// LateStaticBindingDemo below.
$created = Scaffolding\makePen();
$created->write(); // function return type
// MUST NOT appear: refill() (private)
$absolute = \Demo\Scaffolding\makePen(); // leading-backslash (absolute) call
$absolute->write(); // resolves the same as Scaffolding\makePen()
$found = Scaffolding\pickPenOrPencil(); // Scaffolding\Pen|Scaffolding\Pencil union
$found->label(); // available on both types
}
}
// ── Late Static Binding ─────────────────────────────────────────────────────
class LateStaticBindingDemo extends Scaffolding\Pen
{
public function demo(): void
{
// These four forward late static binding, so `static` stays open:
// it is at least LateStaticBindingDemo, and a subclass of this class
// would get itself. Hover shows the bound as `static(...)`.
$forwarded = $this->rename('Bold');
$forwarded->write();
$viaSelf = self::make();
$viaStatic = static::make();
$viaParent = parent::make();
$viaSelf->write();
$viaStatic->write();
$viaParent->write(); // still bound here, not Scaffolding\Pen
// A first-class callable resolves to the same type as the direct
// call it stands for.
$callable = $this->rename(...);
$callable('Bold')->write();
// Naming the class closes it again, even from inside the hierarchy.
$pinned = Scaffolding\Pen::make(); // exactly Scaffolding\Pen
$pinned->write();
}
/** The forwarding forms, handed back so the assertions can check them. */
public function forwardedInstances(): array
{
return [self::make(), static::make(), parent::make()];
}
}
// ── Type Narrowing ──────────────────────────────────────────────────────────
class TypeNarrowingDemo
{
public function demo(): void
{
$specimen = Scaffolding\pickRockOrBanana(); // Scaffolding\Rock|Scaffolding\Banana
if ($specimen instanceof Scaffolding\Rock) {
$specimen->crush(); // narrowed to Scaffolding\Rock
// MUST NOT appear: peel() (Scaffolding\Banana only)
} else {
$specimen->peel(); // narrowed to Scaffolding\Banana (else branch)
// MUST NOT appear: crush() (Scaffolding\Rock only)
}
if (!$specimen instanceof Scaffolding\Rock) {
$specimen->peel(); // negated instanceof
}
// An instanceof check rules out the array and null alternatives
// too, not just the other class in the union.
$picked = Scaffolding\pickRockOrRocks(true); // Scaffolding\Rock|array<Scaffolding\Rock>|null
if ($picked instanceof Scaffolding\Rock) {
Scaffolding\crushOneRock($picked); // narrowed to Scaffolding\Rock
}
$unknown = Scaffolding\getUnknownValue();
if (is_a($unknown, Scaffolding\Rock::class)) {
$unknown->crush(); // is_a() narrowing
}
$target = Scaffolding\getUnknownValue();
assert($target instanceof Scaffolding\Banana);
$target->peel(); // assert() narrowing
// Inline && narrowing — RHS of && sees the narrowed type from LHS
$sample = Scaffolding\pickRockOrBanana();
if ($sample instanceof Scaffolding\Rock && $sample->crush()) {
// $sample is Scaffolding\Rock here too
}
// Short-circuit || narrowing — the right operand of || runs only
// when the left is false, so `!$guard instanceof Scaffolding\Rock` being false
// means $guard IS Scaffolding\Rock in the right operand.
$guard = Scaffolding\pickRockOrBanana();
if (!$guard instanceof Scaffolding\Rock || !$guard->crush()) {
// guard clause body
}
// The same holds when the subject's declared type names no class:
// `object` is subsumed by the checked class and `string` is ruled
// out by the check succeeding, so nothing but Scaffolding\Rock
// survives into the right operand.
$looked = Scaffolding\lookUpSpecimen(true); // object|string
if (!$looked instanceof Scaffolding\Rock || !Scaffolding\crushOneRock($looked)) {
// guard clause body
}
// A boolean holding the result of an instanceof check carries the
// check with it: testing the boolean narrows the original subject.
$stored = Scaffolding\pickRockOrBanana();
$isRock = $stored instanceof Scaffolding\Rock;
if ($isRock) {
$stored->crush(); // narrowed to Scaffolding\Rock via $isRock
}
echo $isRock ? $stored->crush() : $stored->peel(); // both branches narrowed
// The value a ternary arm *yields* is narrowed too, not just the
// members reachable inside it.
$chosen = $isRock ? $stored : new Scaffolding\Rock();
Scaffolding\crushOneRock($chosen); // Scaffolding\Rock, from the $isRock arm
// A boolean holding an `||` chain stands for the whole disjunction:
// the subject is one of the classes it lists.
$shelved = Scaffolding\pickRockOrBanana();
$isKnown = $shelved instanceof Scaffolding\Rock || $shelved instanceof Scaffolding\Banana;
if ($isKnown) {
$shelved->weigh(); // Scaffolding\Rock|Scaffolding\Banana
}
// A variable a guarded branch fills stands for the guard itself:
// reaching the `!== null` test means the branch ran, so whatever
// it narrowed is narrowed again.
$weighed = Scaffolding\pickRockOrBanana();
$label = null;
if ($weighed instanceof Scaffolding\Rock) {
$label = new Scaffolding\SpecimenLabel('rock');
}
if ($label !== null) {
Scaffolding\crushOneRock($weighed); // Scaffolding\Rock, proven by $label
}
// The negated form works as a guard clause too.
$held = Scaffolding\pickRockOrBanana();
$isBanana = $held instanceof Scaffolding\Banana;
if (!$isBanana) {
return;
}
$held->peel(); // narrowed to Scaffolding\Banana after the guard
}
public function guardClause(): void
{
// Guard-clause form of the same union: after the throw, only the
// class survives — the array and null alternatives are gone.
$picked = Scaffolding\pickRockOrRocks(true); // Scaffolding\Rock|array<Scaffolding\Rock>|null
if (!$picked instanceof Scaffolding\Rock) {
throw new \RuntimeException('expected one rock');
}
Scaffolding\crushOneRock($picked); // narrowed to Scaffolding\Rock
}
}
// ── Compound & Non-Variable-Subject Narrowing ──────────────────────────────
// instanceof / assert narrowing survives compound && / || conditions and
// applies to property, array-indexed, and inline-assignment subjects, not
// just a single negated variable guard.
class CompoundNarrowingDemo
{
public function demo(Scaffolding\SpecimenHolder $holder): void
{
// && chain: a later conjunct (and the body) see the narrowing
// established by the first conjunct.
if ($holder->item instanceof Scaffolding\Rock && $holder->item->crush() === 'smash!') {
$holder->item->crush(); // property narrowed to Scaffolding\Rock
}
// Heterogeneous || guard clause: De Morgan narrows the property
// subject after the early return.
if (!$holder instanceof Scaffolding\SpecimenHolder || !$holder->item instanceof Scaffolding\Rock) {
return;
}
$holder->item->crush(); // property narrowed to Scaffolding\Rock
// Inline assignment in the condition narrows the assigned variable.
if (($picked = $holder->maybe()) instanceof Scaffolding\Banana) {
$picked->peel(); // inline-assigned var narrowed
}
// A pair of `!` cancels, so a doubly negated guard proves exactly
// what the bare one does. Blade's `@unless (!$specimen)` compiles
// to this shape, which is how it turns up without being written.
$specimen = $holder->maybe(); // Scaffolding\Rock|Scaffolding\Banana|null
if (!(!$specimen)) {
$specimen->weigh(); // null dropped, as with `if ($specimen)`
}
// The fold applies per conjunct, so wrapping one of them costs the
// chain nothing.
if (!(!$specimen) && !(!($specimen instanceof Scaffolding\Rock))) {
$specimen->crush(); // narrowed to Scaffolding\Rock
}
}
/**
* A check on a call narrows the call itself, so the same call
* written again inside the branch resolves to what the check proved
* rather than to the declared return type. The arguments are part
* of what makes two occurrences the same call, so `lookUp('rock')`
* and `lookUp('banana')` are narrowed apart from one another.
*/
public function repeatedCall(Scaffolding\SpecimenHolder $holder): string
{
if ($holder->maybe() instanceof Scaffolding\Rock) {
return $holder->maybe()->crush(); // call narrowed to Scaffolding\Rock
}
if ($holder->lookUp('rock') instanceof Scaffolding\Rock) {
return $holder->lookUp('rock')->crush(); // narrowed to Scaffolding\Rock
}
// Try: put the cursor after the `->` below. Nothing has been
// proved about this call, so it still offers `Rock|Banana|null`.
// $holder->lookUp('banana')->
return '';
}
/**
* A ternary condition proves the same thing an `if` condition does,
* and its arms are where the repeated call gets written: the
* re-check-and-reuse idiom for a call that reports "nothing here"
* with a value rather than an exception.
*/
public function repeatedCallInTernary(Scaffolding\SpecimenHolder $holder): string
{
// The true arm re-evaluates the same call, and the check has
// already ruled out the `null` it could have answered, so the
// result satisfies a parameter that does not accept `null`.
$found = $holder->lookUp('rock') !== null
? $holder->lookUp('rock') // narrowed to Scaffolding\Rock|Banana
: new Scaffolding\Rock();
// The else arm of the negated spelling carries the same proof.
$weight = $holder->lookUp('rock') === null
? 0.0
: $holder->lookUp('rock')->weigh(); // narrowed, so `weigh()` resolves
return $holder->labelFor($found)->render() . $weight;
}
/**
* A proof lasts as long as the state it was made about. What a later
* call on the same receiver does to it is read off the declaration:
* `@phpstan-pure` keeps it, a method that hands nothing back was called
* for its effect and drops it, and `@impure` drops it even though the
* call returns a value. Anything else computes a value and keeps it.
*/
public function callInvalidation(Scaffolding\SpecimenHolder $holder): string
{
if ($holder->lookUp('rock') instanceof Scaffolding\Rock) {
$label = $holder->shelfLabel(); // pure — the proof stands
$count = $holder->shelfCount(); // returns a value — so does this
$rock = $holder->lookUp('rock'); // still Scaffolding\Rock
$rock->crush();
$holder->restock(); // returns nothing — the shelf moved on
// Try: put the cursor after the `->` below. The call is back to
// `Rock|Banana|null`, so `crush()` is no longer offered alone.
// $holder->lookUp('rock')->
return $label . $count;
}
if ($holder->lookUp('rock') instanceof Scaffolding\Rock) {
$holder->rotate(); // @impure — same effect on the proof
// Try: put the cursor after the `->` below. Same widened call.
// $holder->lookUp('rock')->
}
return '';
}
/** @param array<Scaffolding\Rock|Scaffolding\Banana> $items */
public function indexed(array $items): void
{
// Integer-indexed subject narrowed by a guard clause.
if (!$items[0] instanceof Scaffolding\Rock) {
return;
}
$items[0]->crush(); // element narrowed to Scaffolding\Rock
}
/** @param array<string, mixed> $bag */
public function untypedIndexed(array $bag): void
{
// The element type is unknown (mixed), but a guard clause still
// narrows the array-index subject to the checked class.
if (!$bag['specimen'] instanceof Scaffolding\Rock) {
return;
}
$bag['specimen']->crush(); // mixed index narrowed to Scaffolding\Rock
}
public function arrow(): callable
{
// An untyped arrow-function parameter narrowed by an earlier `&&`
// conjunct is visible to the member access in a later conjunct.
return fn($specimen) => $specimen instanceof Scaffolding\Rock && $specimen->crush() === 'smash!';
}
/**
* Two checks that both hold prove the subject is both types at once,
* so it satisfies a parameter naming either one on its own.
*/
public function bothAtOnce(object $specimen): string
{
if ($specimen instanceof Scaffolding\Rock && $specimen instanceof Scaffolding\Labelled) {
$this->takesRock($specimen); // Scaffolding\Rock&Scaffolding\Labelled satisfies Scaffolding\Rock
$this->takesLabelled($specimen); // ... and Scaffolding\Labelled
return $specimen->crush() . ':' . $specimen->label();
}
return '';
}
/**
* `assert()` reaches the same conclusion about a value already typed as
* a class it does not nominally implement, which is how a test doubles
* a concrete dependency with a mock.
*/
public function assertedBoth(Scaffolding\Rock $rock): string
{
assert($rock instanceof Scaffolding\Labelled);
$this->takesRock($rock); // still a Scaffolding\Rock
$this->takesLabelled($rock); // and now a Scaffolding\Labelled too
return $rock->crush() . ':' . $rock->label();
}
private function takesRock(Scaffolding\Rock $rock): void {}
private function takesLabelled(Scaffolding\Labelled $labelled): void {}
}
// ── `match (true)` Arm Narrowing ───────────────────────────────────────────
// A `match (true)` arm's condition proves inside the arm's result exactly
// what the equivalent `if` proves inside its body, and it proves it for
// whatever the result builds, not just for a value it names directly.
// Reaching a later arm means every arm above it was tested and failed, so
// the `default` reads what their conditions ruled out.
class MatchArmNarrowingDemo
{
public function describe(Scaffolding\SpecimenHolder $holder, string $name): string
{
$specimen = $holder->lookUp($name); // Scaffolding\Rock|Scaffolding\Banana|null
return match (true) {
$specimen instanceof Scaffolding\Rock => $specimen->crush(),
$specimen !== null => (string) $specimen->weigh(), // null ruled out by this arm
default => 'nothing',
};
}
/**
* The arm's proof reaches the elements of an array it builds, so this
* is a list of plain floats rather than of nullable ones.
*
* @return list<float>
*/
public function weights(Scaffolding\SpecimenHolder $holder): array
{
$first = $holder->lookUp('rock'); // Scaffolding\Rock|Scaffolding\Banana|null
$second = $holder->lookUp('banana'); // same, and this one is null
return match (true) {
$first !== null && $second !== null => [$first->weigh(), $second->weigh()],
$first !== null => [$first->weigh()],
default => [],
};
}
/**
* An arm listing several conditions runs when any one of them matched,
* so only what all of them prove holds inside it: here both name the
* same class, and neither says anything about `$other`.
*/
public function eitherCondition(Scaffolding\SpecimenHolder $holder): string
{
$specimen = $holder->lookUp('rock');
$other = $holder->lookUp('banana');
return match (true) {
$specimen instanceof Scaffolding\Rock,
$specimen instanceof Scaffolding\Rock && $other !== null => $specimen->crush(),
default => 'nothing',
};
}
/** The `default` sees the inverse of every arm above it. */
public function fallback(Scaffolding\SpecimenHolder $holder): float
{
$specimen = $holder->lookUp('rock');
return match (true) {
$specimen === null => 0.0,
default => $specimen->weigh(), // the arm above ruled the null out
};
}
}
// ── A `?->` Chain Compared to a Value That Cannot Be Null ───────────────────
// A chain that short-circuited holds `null`, and `null` is never identical
// to a value whose type excludes it. So the comparison holding proves the
// chain ran, which is a proof about every receiver it would have
// short-circuited on, including through the plain `->` links written after
// the `?->`.
class NullsafeComparisonDemo
{
public function sameWeight(Scaffolding\SpecimenHolder $holder): string
{
$specimen = $holder->lookUp('rock'); // Scaffolding\Rock|Scaffolding\Banana|null
if ($specimen?->weigh() === $holder->item->weigh()) {
return (string) $specimen->weigh(); // null dropped: the chain must have run
}
// The `!==` spelling proves the same thing where it fails.
if ($specimen?->weigh() !== $holder->item->weigh()) {
return 'different';
}
return (string) $specimen->weigh(); // null dropped past the guard too
}
/**
* Nothing is proved when the other side can be null as well: both
* sides holding `null` is one of the ways the comparison succeeds.
*/
public function bothMayBeNull(Scaffolding\SpecimenHolder $holder): string
{
$specimen = $holder->lookUp('rock');
if ($specimen?->weigh() === $holder->lookUp('banana')?->weigh()) {
// Try: put the cursor after the `?->` below. `$specimen` is
// still `Scaffolding\Rock|Scaffolding\Banana|null` here.
return (string) $specimen?->weigh();
}
return 'different';
}
}
// ── Variables Filled Together in One Branch Share Their Null ────────────────
// `$label` is written on exactly the path that leaves `$specimen` holding a
// value, so the two are null together or not at all. The merge at the end of
// the branch records that, which is what lets a later check on one of them
// settle the other, even though the check never names it.
class CorrelatedNullDemo
{
public function describe(Scaffolding\SpecimenHolder $holder, string $name): string
{
$label = null;
$specimen = null;
if ($name !== '') {
$specimen = $holder->lookUp($name);
if ($specimen !== null) {
$label = $holder->labelFor($specimen);
}
}
if ($specimen !== null) {
// Try: put the cursor after the `->` below. `$label` is a
// `Scaffolding\SpecimenLabel` here rather than a nullable one:
// the only path that leaves `$specimen` holding a value is the
// one that filled `$label` too.
return $label->render();
}
return 'nothing on the shelf';
}
/**
* Two variables filled under conditions of their own are not a pair,
* however alike the branches look, so `$label` keeps its `null` here.
*/
public function unrelated(bool $wantSpecimen, bool $wantLabel): string
{
$label = null;
$specimen = null;
if ($wantSpecimen) {
$specimen = new Scaffolding\Rock();
}
if ($wantLabel) {
$label = new Scaffolding\SpecimenLabel('1kg');
}
if ($specimen !== null) {
// `$label` is still `Scaffolding\SpecimenLabel|null` here, which
// is why the `?->` is the only safe way to read it.
return $label?->render() ?? 'unlabelled';
}
return 'nothing on the shelf';
}
}
// ── Scalar Guards in Compound Conditions and Ternaries ──────────────────────
// The `is_*` family, null checks, and comparisons narrow wherever they are
// written: each operand of a negated `||` guard, both arms of a ternary in any
// position, and an assignment made inside an `elseif` condition.
class ScalarGuardNarrowingDemo
{
/**
* Falling through `if (!guard1 || !guard2) { return; }` means every
* operand was false, so each one's inverse holds afterwards.
*/
public function rejectEverythingElse(string|array|null $payload): string
{
if (!is_string($payload) || $payload === '') {
return 'skipped';
}
// `!is_string` ruled out the array and null halves, and `=== ''`
// refines what is left to non-empty-string.
return Scaffolding\takesNonEmptyString($payload); // non-empty-string
}
/** Each arm of a ternary is resolved under its own polarity. */
public function eitherArm(string|array|null $period): string
{
$chosen = is_string($period) ? $period : 'today';
// The same ternary in argument position narrows identically.
return Scaffolding\takesGradeString(is_string($period) ? $period : $chosen);
}
/** A nested ternary's else arm carries the outer condition's inverse. */
public function nested(string|int|null $value): string
{
return is_string($value)
? $value // string
: (is_int($value) ? (string) $value : 'none');
}
/**
* A truthy check rules out every value that can only ever be false,
* not just `null` and `false`.
*
* The `?? []` is the usual way a union like this appears: the default
* is not of the value's own type, so what comes out spans both. An
* empty array is false in PHP, so the guard below leaves only the
* string half and `explode()` is handed what it asks for.
*
* @return list<string>
*/
public function onlyWhatCanBeTrue(): array
{
$markets = Scaffolding\scaffoldingReadSetting('markets') ?? [];
if ($markets) {
return explode(',', $markets); // string, no array{} left
}
return [];
}
/**
* What is only *sometimes* false is kept: a plain `string` still holds
* `''`, so the guard narrows it no further than the declaration does.
*/
public function whatMayStillBeEither(string $label): string
{
if ($label) {
return Scaffolding\takesGradeString($label); // still string
}
return 'unlabelled';
}
/** An assignment in an `elseif` condition narrows what it wrote. */
public function fromElseif(bool $skip, string|array|null $raw): string
{
if ($skip) {
return 'skipped';
} elseif ($found = Scaffolding\scaffoldingReadPayload($raw)) {
return Scaffolding\takesStringOrArray($found); // string|array, never null
}
return 'empty';
}
/**
* A key expression keeps its own domain, so a map built under `string`
* keys really is `array<string, string>` rather than `array<int|string, …>`.
*
* @param list<Scaffolding\LabelledRock> $specimens
* @return array<string, string>
*/
public function labelMap(array $specimens): array
{
$labels = [];
foreach ($specimens as $specimen) {
$labels[$specimen->label()] = $specimen->crush();
}
return $labels; // array<string, string>
}
/**
* An `int` counter used as a write key stays an `int` key, whether it
* steps before or after the read.
*
* @return array<int, string>
*/
public function numberedLines(): array
{
$line = 0;
$numbered = [];
foreach (['first', 'second'] as $text) {
$numbered[++$line] = $text;
}
return $numbered; // array<int, string>
}
}
// ── Discriminating-Property Narrowing ───────────────────────────────────────
// A union of object types is narrowed by a check on a property only some of
// its members could have passed, the way TypeScript discriminates on a tag.
class PropertyDiscriminantDemo
{
/**
* A type guard on the property rules out the member that declares that
* property with an incompatible type.
*/
public function byTypeGuard(): int
{
$tag = Scaffolding\pickTag(); // Scaffolding\TextTag|Scaffolding\NumberTag
if (is_string($tag->tag)) {
return $tag->letters(); // narrowed to Scaffolding\TextTag
// MUST NOT appear: digits() (Scaffolding\NumberTag only)
}
return $tag->digits(); // narrowed to Scaffolding\NumberTag (else branch)
}
/**
* A tagged union: each member pins its tag to one value, so comparing
* against that value picks the member out.
*/
public function byTagValue(): float
{
$sample = Scaffolding\pickWeighing(); // Scaffolding\Weighed|Scaffolding\Unweighed
if ($sample->state === 'weighed') {
return $sample->grams; // narrowed to Scaffolding\Weighed
// MUST NOT appear: reason() (Scaffolding\Unweighed only)
}
return 0.0;
}
}
// ── property_exists() / method_exists() Narrowing ───────────────────────────
// A member-existence guard proves the (otherwise unknown) member for the rest
// of the branch, mirroring PHPStan's `object&hasProperty(...)` intersection.
// The proof is confined to the guarded branch: the same access outside it is
// still flagged.
class MemberExistsNarrowingDemo
{
public function property(Scaffolding\ApiResponse $response): ?string
{
// property_exists() proves the dynamically-populated property, so the
// access resolves instead of reporting an unknown member.
if (property_exists($response, 'errorMessage') && is_string($response->errorMessage)) {
return $response->errorMessage; // proven by property_exists
}
return null;
}
public function guardClause(Scaffolding\ApiResponse $response): string
{
// Negated guard clause: after the early return the property exists.
if (!property_exists($response, 'detail')) {
return 'none';
}
return (string) $response->detail; // proven after the guard
}
public function issetGuard(Scaffolding\ApiResponse $response): ?string
{
// isset($obj->prop) proves the property exists (and is non-null)
// for the guarded branch, exactly like property_exists().
if (isset($response->errorMessage)) {
return (string) $response->errorMessage; // proven by isset
}
return null;
}
public function ternary(Scaffolding\ApiResponse $response): string
{
// Both member-existence guards prove the property in a ternary's
// then-branch, mirroring the if-statement form.
$viaPropertyExists = property_exists($response, 'detail')
? (string) $response->detail // proven by property_exists
: 'none';
$viaIsset = isset($response->errorMessage)
? (string) $response->errorMessage // proven by isset
: 'none';
return $viaPropertyExists . '|' . $viaIsset;
}
public function method(Scaffolding\DynamicHandler $handler): void
{
// method_exists() proves the method for the guarded branch.
if (method_exists($handler, 'customHook')) {
$handler->customHook(); // proven by method_exists
}
}
}
// ── Type Guard Narrowing (is_array, is_object, …) ──────────────────────────
class TypeGuardNarrowingDemo
{
/**
* @param null|list<Scaffolding\Pen>|Scaffolding\Pen $input
*/
public function demo(null|array|Scaffolding\Pen $input): void
{
// is_array() narrows the union to the array-like PHPDoc member,
// preserving the generic element type for foreach iteration.
if (is_array($input)) {
foreach ($input as $pen) {
$pen->write(); // list<Scaffolding\Pen> → Scaffolding\Pen
}
}
// Else branch: non-array members survive
if (is_array($input)) {
// array branch
} else {
// $input is null|Scaffolding\Pen here
}
// Guard clause: is_array() + early return
if (is_array($input)) {
return;
}
// $input is null|Scaffolding\Pen after the guard
// is_object() narrows to class members only
$mixed = Scaffolding\pickRockOrBanana(); // Scaffolding\Rock|Scaffolding\Banana
if (is_object($mixed)) {
$mixed->weigh(); // both Scaffolding\Rock and Scaffolding\Banana have weigh()
}
// is_object() narrows mixed → object, suppressing diagnostics
// on dynamic property access (stdClass / object permit any property).
$decoded = json_decode('{}'); // mixed
if (is_object($decoded)) {
echo $decoded->anything; // no diagnostic — object allows any property
}
// Compound && condition: is_object() narrowing propagates
// through the entire condition and into the if-body.
$payload = json_decode('{}'); // mixed
if (is_object($payload) && property_exists($payload, 'name')) {
echo $payload->name; // no diagnostic
}
// A property assigned `new stdClass()` resolves back to stdClass,
// so a nested object graph built up field by field type-checks.
$settings = new \stdClass();
$settings->cache = new \stdClass(); // $settings->cache : stdClass
$settings->cache->ttl = 3600; // no diagnostic on ->ttl
}