phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
use crate::common::create_test_backend;
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;

/// Match expression with `new` instantiations: each arm contributes a
/// possible type, so the variable should show completions from all arms.
#[tokio::test]
async fn test_completion_match_expression_multiple_new_instantiations() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_new.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class ElasticProductReviewIndexService {\n",
        "    public function index(): void {}\n",
        "    public function reindex(): void {}\n",
        "}\n",
        "\n",
        "class ElasticBrandIndexService {\n",
        "    public function index(): void {}\n",
        "    public function bulkDelete(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(string $indexName): void {\n",
        "        $service = match ($indexName) {\n",
        "            'product-reviews' => new ElasticProductReviewIndexService(),\n",
        "            'brands'          => new ElasticBrandIndexService(),\n",
        "            default           => null,\n",
        "        };\n",
        "        $service->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$service->` on line 18
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 18,
                character: 18,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $service-> from match"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            // `index` is on both classes
            assert!(
                labels.iter().any(|l| l.starts_with("index")),
                "Should include index (shared method), got: {:?}",
                labels
            );
            // `reindex` is only on ElasticProductReviewIndexService
            assert!(
                labels.iter().any(|l| l.starts_with("reindex")),
                "Should include reindex from ElasticProductReviewIndexService, got: {:?}",
                labels
            );
            // `bulkDelete` is only on ElasticBrandIndexService
            assert!(
                labels.iter().any(|l| l.starts_with("bulkDelete")),
                "Should include bulkDelete from ElasticBrandIndexService, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression with static method calls: each arm's return type
/// should contribute to the variable's union type.
#[tokio::test]
async fn test_completion_match_expression_static_method_calls() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_static.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Logger {\n",
        "    public function log(string $msg): void {}\n",
        "    /** @return static */\n",
        "    public static function create(): static { return new static(); }\n",
        "}\n",
        "\n",
        "class FileLogger extends Logger {\n",
        "    public function rotate(): void {}\n",
        "}\n",
        "\n",
        "class SyslogLogger extends Logger {\n",
        "    public function facility(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function boot(string $driver): void {\n",
        "        $logger = match ($driver) {\n",
        "            'file'   => FileLogger::create(),\n",
        "            'syslog' => SyslogLogger::create(),\n",
        "        };\n",
        "        $logger->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$logger->` on line 21
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 21,
                character: 17,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $logger-> from match with static calls"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            // Both are Logger subclasses, so `log` should appear
            assert!(
                labels.iter().any(|l| l.starts_with("log")),
                "Should include log (inherited), got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("rotate")),
                "Should include rotate from FileLogger, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("facility")),
                "Should include facility from SyslogLogger, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression with a single arm: the variable should resolve to
/// just that one class.
#[tokio::test]
async fn test_completion_match_expression_single_arm() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_single.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Processor {\n",
        "    public function process(): void {}\n",
        "    public function flush(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(int $mode): void {\n",
        "        $proc = match ($mode) {\n",
        "            1 => new Processor(),\n",
        "            default => new Processor(),\n",
        "        };\n",
        "        $proc->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$proc->` on line 12
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 16,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $proc->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("process")),
                "Should include process from Processor, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("flush")),
                "Should include flush from Processor, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression with `$this->method()` call as arm body: the method's
/// return type should resolve correctly.
#[tokio::test]
async fn test_completion_match_expression_this_method_call() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_method.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class CacheDriver {\n",
        "    public function get(string $key): void {}\n",
        "    public function set(string $key, mixed $val): void {}\n",
        "}\n",
        "\n",
        "class QueueDriver {\n",
        "    public function push(string $job): void {}\n",
        "    public function pop(): void {}\n",
        "}\n",
        "\n",
        "class Factory {\n",
        "    /** @return CacheDriver */\n",
        "    public function makeCache(): CacheDriver { return new CacheDriver(); }\n",
        "    /** @return QueueDriver */\n",
        "    public function makeQueue(): QueueDriver { return new QueueDriver(); }\n",
        "\n",
        "    public function resolve(string $type): void {\n",
        "        $driver = match ($type) {\n",
        "            'cache' => $this->makeCache(),\n",
        "            'queue' => $this->makeQueue(),\n",
        "        };\n",
        "        $driver->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$driver->` on line 22
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 22,
                character: 17,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $driver-> from match with method calls"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            // CacheDriver methods
            assert!(
                labels.iter().any(|l| l.starts_with("get")),
                "Should include get from CacheDriver, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("set")),
                "Should include set from CacheDriver, got: {:?}",
                labels
            );
            // QueueDriver methods
            assert!(
                labels.iter().any(|l| l.starts_with("push")),
                "Should include push from QueueDriver, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("pop")),
                "Should include pop from QueueDriver, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression at the top level (outside a class): `$var = match(…) { … }`
/// should still resolve all arm types.
#[tokio::test]
async fn test_completion_match_expression_top_level() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_top_level.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Alpha {\n",
        "    public function alphaMethod(): void {}\n",
        "}\n",
        "\n",
        "class Beta {\n",
        "    public function betaMethod(): void {}\n",
        "}\n",
        "\n",
        "$x = match (true) {\n",
        "    true  => new Alpha(),\n",
        "    false => new Beta(),\n",
        "};\n",
        "$x->\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$x->` on line 13
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 13,
                character: 4,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for top-level $x-> from match"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("alphaMethod")),
                "Should include alphaMethod from Alpha, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("betaMethod")),
                "Should include betaMethod from Beta, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression with property access in an arm body:
/// `'key' => $this->prop` where `prop` is typed should resolve correctly.
#[tokio::test]
async fn test_completion_match_expression_property_access() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_prop.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Connection {\n",
        "    public function query(string $sql): void {}\n",
        "}\n",
        "\n",
        "class Mailer {\n",
        "    public function send(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    /** @var Connection */\n",
        "    private Connection $db;\n",
        "    /** @var Mailer */\n",
        "    private Mailer $mailer;\n",
        "\n",
        "    public function resolve(string $name): void {\n",
        "        $svc = match ($name) {\n",
        "            'db'     => $this->db,\n",
        "            'mailer' => $this->mailer,\n",
        "        };\n",
        "        $svc->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$svc->` on line 20
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 20,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $svc-> from match with property access"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("query")),
                "Should include query from Connection, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("send")),
                "Should include send from Mailer, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Cross-file match expression: arm bodies that instantiate classes from
/// other files should still resolve via PSR-4.
#[tokio::test]
async fn test_completion_match_expression_cross_file() {
    use crate::common::create_psr4_workspace;

    let composer = r#"{
        "autoload": {
            "psr-4": {
                "App\\": "src/"
            }
        }
    }"#;

    let handler_php = concat!(
        "<?php\n",
        "namespace App;\n",
        "\n",
        "use App\\Services\\SearchService;\n",
        "use App\\Services\\IndexService;\n",
        "\n",
        "class Handler {\n",
        "    public function handle(string $action): void {\n",
        "        $svc = match ($action) {\n",
        "            'search' => new SearchService(),\n",
        "            'index'  => new IndexService(),\n",
        "        };\n",
        "        $svc->\n",
        "    }\n",
        "}\n",
    );

    let search_service_php = concat!(
        "<?php\n",
        "namespace App\\Services;\n",
        "\n",
        "class SearchService {\n",
        "    public function search(string $query): void {}\n",
        "    public function suggest(string $prefix): void {}\n",
        "}\n",
    );

    let index_service_php = concat!(
        "<?php\n",
        "namespace App\\Services;\n",
        "\n",
        "class IndexService {\n",
        "    public function reindex(): void {}\n",
        "    public function drop(): void {}\n",
        "}\n",
    );

    let (backend, _dir) = create_psr4_workspace(
        composer,
        &[
            ("src/Handler.php", handler_php),
            ("src/Services/SearchService.php", search_service_php),
            ("src/Services/IndexService.php", index_service_php),
        ],
    );

    let uri = Url::parse("file:///src/Handler.php").unwrap();
    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: handler_php.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$svc->` on line 12
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for cross-file match expression"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("search")),
                "Should include search from SearchService, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("suggest")),
                "Should include suggest from SearchService, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("reindex")),
                "Should include reindex from IndexService, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("drop")),
                "Should include drop from IndexService, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression followed by an unconditional reassignment: the match
/// types should be replaced by the final assignment.
#[tokio::test]
async fn test_completion_match_expression_overridden_by_reassignment() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_override.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Foo {\n",
        "    public function fooMethod(): void {}\n",
        "}\n",
        "\n",
        "class Bar {\n",
        "    public function barMethod(): void {}\n",
        "}\n",
        "\n",
        "class Baz {\n",
        "    public function bazMethod(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(int $x): void {\n",
        "        $obj = match ($x) {\n",
        "            1 => new Foo(),\n",
        "            2 => new Bar(),\n",
        "        };\n",
        "        $obj = new Baz();\n",
        "        $obj->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$obj->` on line 20
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 20,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $obj->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            // The unconditional reassignment `$obj = new Baz()` should
            // override the match expression types.
            assert!(
                labels.iter().any(|l| l.starts_with("bazMethod")),
                "Should include bazMethod from Baz (final assignment), got: {:?}",
                labels
            );
            assert!(
                !labels.iter().any(|l| l.starts_with("fooMethod")),
                "Should NOT include fooMethod from Foo (overridden), got: {:?}",
                labels
            );
            assert!(
                !labels.iter().any(|l| l.starts_with("barMethod")),
                "Should NOT include barMethod from Bar (overridden), got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression with three distinct arms to verify all types accumulate.
#[tokio::test]
async fn test_completion_match_expression_three_arms() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_three.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Redis {\n",
        "    public function redisGet(): void {}\n",
        "}\n",
        "\n",
        "class Memcached {\n",
        "    public function memGet(): void {}\n",
        "}\n",
        "\n",
        "class FileCache {\n",
        "    public function fileGet(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function make(string $driver): void {\n",
        "        $cache = match ($driver) {\n",
        "            'redis'     => new Redis(),\n",
        "            'memcached' => new Memcached(),\n",
        "            'file'      => new FileCache(),\n",
        "        };\n",
        "        $cache->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$cache->` on line 20
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 20,
                character: 16,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $cache-> with three match arms"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("redisGet")),
                "Should include redisGet from Redis, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("memGet")),
                "Should include memGet from Memcached, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("fileGet")),
                "Should include fileGet from FileCache, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression that uses `app()->make(Foo::class)` style calls in
/// arms — tests the text-based method call resolution fallback path.
#[tokio::test]
async fn test_completion_match_expression_method_call_on_variable() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_method_var.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Printer {\n",
        "    public function print(): void {}\n",
        "}\n",
        "\n",
        "class Scanner {\n",
        "    public function scan(): void {}\n",
        "}\n",
        "\n",
        "class DeviceFactory {\n",
        "    /** @return Printer */\n",
        "    public function createPrinter(): Printer { return new Printer(); }\n",
        "    /** @return Scanner */\n",
        "    public function createScanner(): Scanner { return new Scanner(); }\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(string $type): void {\n",
        "        $factory = new DeviceFactory();\n",
        "        $device = match ($type) {\n",
        "            'print' => $factory->createPrinter(),\n",
        "            'scan'  => $factory->createScanner(),\n",
        "        };\n",
        "        $device->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$device->` on line 23
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 23,
                character: 17,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $device-> from match with method calls on variable"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("print")),
                "Should include print from Printer, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("scan")),
                "Should include scan from Scanner, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// Match expression inside a conditional block: the match variable's
/// types should be treated as conditional (appended to, not replacing).
#[tokio::test]
async fn test_completion_match_expression_inside_if_block() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_in_if.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class DefaultService {\n",
        "    public function defaultOp(): void {}\n",
        "}\n",
        "\n",
        "class SpecialA {\n",
        "    public function specialA(): void {}\n",
        "}\n",
        "\n",
        "class SpecialB {\n",
        "    public function specialB(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(bool $cond, int $x): void {\n",
        "        $svc = new DefaultService();\n",
        "        if ($cond) {\n",
        "            $svc = match ($x) {\n",
        "                1 => new SpecialA(),\n",
        "                2 => new SpecialB(),\n",
        "            };\n",
        "        }\n",
        "        $svc->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor after `$svc->` on line 22
    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 22,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $svc-> with match inside if"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            // DefaultService from before the if, plus SpecialA and SpecialB
            // from the conditional match arms
            assert!(
                labels.iter().any(|l| l.starts_with("defaultOp")),
                "Should include defaultOp from DefaultService, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("specialA")),
                "Should include specialA from SpecialA, got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("specialB")),
                "Should include specialB from SpecialB, got: {:?}",
                labels
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

/// When a variable holds a union type from a match expression, branch-only
/// members should show the originating class in `label_details.description`.
/// Intersection members should not have a class-name description.
#[tokio::test]
async fn test_completion_match_expression_detail_shows_merged_classes() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///match_detail_merge.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class ElasticProductReviewIndexService {\n",
        "    public function index(): void {}\n",
        "    public function reindex(): void {}\n",
        "}\n",
        "\n",
        "class ElasticBrandIndexService {\n",
        "    public function index(): void {}\n",
        "    public function bulkDelete(): void {}\n",
        "}\n",
        "\n",
        "class App {\n",
        "    public function run(string $indexName): void {\n",
        "        $service = match ($indexName) {\n",
        "            'product-reviews' => new ElasticProductReviewIndexService(),\n",
        "            'brands'          => new ElasticBrandIndexService(),\n",
        "            default           => null,\n",
        "        };\n",
        "        $service->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 18,
                character: 18,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for $service->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            // `index` is on both classes — intersection member should
            // show both class names in label_details.
            let index_item = items
                .iter()
                .find(|i| i.filter_text.as_deref() == Some("index"))
                .expect("Should have an index completion item");
            let index_desc = index_item
                .label_details
                .as_ref()
                .and_then(|ld| ld.description.as_deref())
                .unwrap_or("");
            assert!(
                index_desc.contains("ElasticProductReviewIndexService")
                    && index_desc.contains("ElasticBrandIndexService"),
                "Shared method 'index' should show both class names, got: {:?}",
                index_desc
            );

            // `reindex` is only on ElasticProductReviewIndexService —
            // branch-only member should show that class in label_details.
            let reindex_item = items
                .iter()
                .find(|i| i.filter_text.as_deref() == Some("reindex"))
                .expect("Should have a reindex completion item");
            let reindex_desc = reindex_item
                .label_details
                .as_ref()
                .and_then(|ld| ld.description.as_deref())
                .unwrap_or("");
            assert!(
                reindex_desc.contains("ElasticProductReviewIndexService")
                    && !reindex_desc.contains("ElasticBrandIndexService"),
                "Branch-only method 'reindex' should show only its class in label_details, got: {:?}",
                reindex_desc
            );

            // `bulkDelete` is only on ElasticBrandIndexService.
            let bulk_item = items
                .iter()
                .find(|i| i.filter_text.as_deref() == Some("bulkDelete"))
                .expect("Should have a bulkDelete completion item");
            let bulk_desc = bulk_item
                .label_details
                .as_ref()
                .and_then(|ld| ld.description.as_deref())
                .unwrap_or("");
            assert!(
                bulk_desc.contains("ElasticBrandIndexService")
                    && !bulk_desc.contains("ElasticProductReviewIndexService"),
                "Branch-only method 'bulkDelete' should show only its class in label_details, got: {:?}",
                bulk_desc
            );
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}