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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
//! Integration tests for PHP version-aware stub filtering.
//!
//! Tests that `#[PhpStormStubsElementAvailable]` attributes on functions,
//! methods, and parameters are respected when a target PHP version is set.

use crate::common::create_test_backend;
use phpantom_lsp::Backend;
use phpantom_lsp::types::PhpVersion;
use tower_lsp::lsp_types::{HoverContents, Position};

// ─── PhpVersion parsing ─────────────────────────────────────────────────────

#[test]
fn parse_caret_constraint() {
    let v = PhpVersion::from_composer_constraint("^8.4").unwrap();
    assert_eq!(v, PhpVersion::new(8, 4));
}

#[test]
fn parse_gte_constraint() {
    let v = PhpVersion::from_composer_constraint(">=8.3").unwrap();
    assert_eq!(v, PhpVersion::new(8, 3));
}

#[test]
fn parse_tilde_constraint() {
    let v = PhpVersion::from_composer_constraint("~8.2").unwrap();
    assert_eq!(v, PhpVersion::new(8, 2));
}

#[test]
fn parse_wildcard_constraint() {
    let v = PhpVersion::from_composer_constraint("8.1.*").unwrap();
    assert_eq!(v, PhpVersion::new(8, 1));
}

#[test]
fn parse_exact_version() {
    let v = PhpVersion::from_composer_constraint("8.3.1").unwrap();
    assert_eq!(v, PhpVersion::new(8, 3));
}

#[test]
fn parse_major_only() {
    let v = PhpVersion::from_composer_constraint("^8").unwrap();
    assert_eq!(v, PhpVersion::new(8, 0));
}

#[test]
fn parse_range_takes_first() {
    // ">=8.0 <8.4" → first match wins → 8.0
    let v = PhpVersion::from_composer_constraint(">=8.0 <8.4").unwrap();
    assert_eq!(v, PhpVersion::new(8, 0));
}

#[test]
fn parse_pipe_separated() {
    let v = PhpVersion::from_composer_constraint("^7.4|^8.0").unwrap();
    assert_eq!(v, PhpVersion::new(7, 4));
}

#[test]
fn parse_empty_returns_none() {
    assert!(PhpVersion::from_composer_constraint("").is_none());
}

#[test]
fn parse_garbage_returns_none() {
    assert!(PhpVersion::from_composer_constraint("not-a-version").is_none());
}

#[test]
fn default_version_is_8_5() {
    let v = PhpVersion::default();
    assert_eq!(v, PhpVersion::new(8, 5));
}

// ─── matches_range ──────────────────────────────────────────────────────────

#[test]
fn matches_range_unbounded() {
    let v = PhpVersion::new(8, 4);
    assert!(v.matches_range(None, None));
}

#[test]
fn matches_range_from_only_matches() {
    let v = PhpVersion::new(8, 4);
    assert!(v.matches_range(Some(PhpVersion::new(8, 0)), None));
}

#[test]
fn matches_range_from_only_too_low() {
    let v = PhpVersion::new(7, 4);
    assert!(!v.matches_range(Some(PhpVersion::new(8, 0)), None));
}

#[test]
fn matches_range_to_only_matches() {
    let v = PhpVersion::new(7, 4);
    assert!(v.matches_range(None, Some(PhpVersion::new(7, 4))));
}

#[test]
fn matches_range_to_only_too_high() {
    let v = PhpVersion::new(8, 0);
    assert!(!v.matches_range(None, Some(PhpVersion::new(7, 4))));
}

#[test]
fn matches_range_exact() {
    let v = PhpVersion::new(8, 0);
    assert!(v.matches_range(Some(PhpVersion::new(8, 0)), Some(PhpVersion::new(8, 0))));
}

#[test]
fn matches_range_within() {
    let v = PhpVersion::new(8, 1);
    assert!(v.matches_range(Some(PhpVersion::new(8, 0)), Some(PhpVersion::new(8, 4))));
}

#[test]
fn matches_range_outside_below() {
    let v = PhpVersion::new(7, 4);
    assert!(!v.matches_range(Some(PhpVersion::new(8, 0)), Some(PhpVersion::new(8, 4))));
}

#[test]
fn matches_range_outside_above() {
    let v = PhpVersion::new(8, 5);
    assert!(!v.matches_range(Some(PhpVersion::new(8, 0)), Some(PhpVersion::new(8, 4))));
}

// ─── Composer version detection ─────────────────────────────────────────────

#[test]
fn detect_version_from_require_php() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("composer.json"),
        r#"{ "require": { "php": "^8.4" } }"#,
    )
    .unwrap();
    let v = phpantom_lsp::composer::detect_php_version(dir.path()).unwrap();
    assert_eq!(v, PhpVersion::new(8, 4));
}

#[test]
fn detect_version_from_platform_php() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("composer.json"),
        r#"{ "config": { "platform": { "php": "8.3.1" } }, "require": { "php": "^8.4" } }"#,
    )
    .unwrap();
    // platform.php takes priority over require.php
    let v = phpantom_lsp::composer::detect_php_version(dir.path()).unwrap();
    assert_eq!(v, PhpVersion::new(8, 3));
}

#[test]
fn detect_version_no_composer_json() {
    let dir = tempfile::tempdir().unwrap();
    let v = phpantom_lsp::composer::detect_php_version(dir.path());
    assert!(v.is_none());
}

#[test]
fn detect_version_no_php_constraint() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("composer.json"),
        r#"{ "require": { "laravel/framework": "^11.0" } }"#,
    )
    .unwrap();
    let v = phpantom_lsp::composer::detect_php_version(dir.path());
    assert!(v.is_none());
}

// ─── Helpers ────────────────────────────────────────────────────────────────

/// Register file content in the backend and return hover result.
fn hover_at(
    backend: &Backend,
    uri: &str,
    content: &str,
    line: u32,
    character: u32,
) -> Option<tower_lsp::lsp_types::Hover> {
    backend.update_ast(uri, content);
    backend.handle_hover(uri, content, Position { line, character })
}

fn hover_text(hover: &tower_lsp::lsp_types::Hover) -> &str {
    match &hover.contents {
        HoverContents::Markup(markup) => &markup.value,
        _ => panic!("Expected MarkupContent"),
    }
}

// ─── Function-level version filtering ───────────────────────────────────────

#[test]
fn function_level_php80_picks_correct_variant() {
    // Two variants of the same function: one for <=7.4, one for >=8.0.
    // With PHP 8.4, only the 8.0+ variant should survive.
    let backend = create_test_backend();
    backend.set_php_version(PhpVersion::new(8, 4));

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

/**
 * @return array|false
 */
#[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')]
function array_combine(array $keys, array $values): array|false {}

/**
 * @return array
 */
#[PhpStormStubsElementAvailable(from: '8.0')]
function array_combine(array $keys, array $values): array {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(
        functions.len(),
        1,
        "should have exactly one function variant"
    );
    // The 8.0+ variant has return type `array` (not `array|false`).
    assert_eq!(
        functions[0]
            .native_return_type
            .as_ref()
            .map(|t| t.to_string())
            .as_deref(),
        Some("array"),
        "should pick the PHP 8.0+ variant"
    );
}

#[test]
fn function_level_php74_picks_legacy_variant() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

#[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')]
function array_combine(array $keys, array $values): array|false {}

#[PhpStormStubsElementAvailable(from: '8.0')]
function array_combine(array $keys, array $values): array {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(7, 4)));
    assert_eq!(functions.len(), 1);
    assert_eq!(
        functions[0]
            .native_return_type
            .as_ref()
            .map(|t| t.to_string())
            .as_deref(),
        Some("array|false"),
        "should pick the PHP 5.3-7.4 variant"
    );
}

#[test]
fn function_without_version_attribute_always_included() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
function always_available(string $arg): string {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions.len(), 1);
    assert_eq!(functions[0].name, "always_available");
}

#[test]
fn function_with_positional_from_argument() {
    // `#[PhpStormStubsElementAvailable('8.1')]` — positional arg = from
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

#[PhpStormStubsElementAvailable('8.1')]
function new_function(): void {}
"#;

    // PHP 8.0 — should be excluded
    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 0)));
    assert_eq!(
        functions.len(),
        0,
        "function should be excluded for PHP 8.0"
    );

    // PHP 8.1 — should be included
    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 1)));
    assert_eq!(
        functions.len(),
        1,
        "function should be included for PHP 8.1"
    );
}

#[test]
fn function_with_to_only() {
    // Available up to 7.4 only
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

#[PhpStormStubsElementAvailable(to: '7.4')]
function legacy_only(): void {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 0)));
    assert_eq!(functions.len(), 0, "should be excluded for PHP 8.0");

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(7, 4)));
    assert_eq!(functions.len(), 1, "should be included for PHP 7.4");
}

// ─── Parameter-level version filtering ──────────────────────────────────────

#[test]
fn parameter_version_filtering_php80() {
    // Like the real array_map stub: one param for 8.0+, another for <=7.4
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

function array_map(
    ?callable $callback,
    #[PhpStormStubsElementAvailable(from: '8.0')] array $array,
    #[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')] $arrays,
    array ...$arrays
): array {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions.len(), 1);
    let params = &functions[0].parameters;

    // Should have: $callback, $array (8.0+), ...$arrays
    // Should NOT have the bare $arrays (5.3-7.4)
    let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(names, vec!["$callback", "$array", "$arrays"]);

    // $array should be typed `array`
    assert_eq!(params[1].type_hint_str().as_deref(), Some("array"));
    assert_eq!(params[1].name, "$array");

    // ...$arrays should be variadic
    assert!(params[2].is_variadic);
}

#[test]
fn parameter_version_filtering_php74() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

function array_map(
    ?callable $callback,
    #[PhpStormStubsElementAvailable(from: '8.0')] array $array,
    #[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')] $arrays,
    array ...$arrays
): array {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(7, 4)));
    assert_eq!(functions.len(), 1);
    let params = &functions[0].parameters;

    // Should have: $callback, $arrays (5.3-7.4 untyped), ...$arrays
    // Should NOT have `array $array` (8.0+)
    let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(names, vec!["$callback", "$arrays", "$arrays"]);

    // The first $arrays (5.3-7.4) has no type hint
    assert_eq!(params[1].type_hint, None);
    assert!(!params[1].is_variadic);

    // The second $arrays is variadic
    assert!(params[2].is_variadic);
}

#[test]
fn parameter_without_version_attribute_always_included() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
function my_func(string $always, int $present): void {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions[0].parameters.len(), 2);
}

#[test]
fn parameter_with_from_only_added_in_later_version() {
    // Parameter added in PHP 7.0
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

function unserialize(string $data, #[PhpStormStubsElementAvailable(from: '7.0')] array $options = []): mixed {}
"#;

    // PHP 7.0+ — should include $options
    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions[0].parameters.len(), 2);

    // PHP 5.6 — should exclude $options
    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(5, 6)));
    assert_eq!(functions[0].parameters.len(), 1);
    assert_eq!(functions[0].parameters[0].name, "$data");
}

// ─── Method-level version filtering ─────────────────────────────────────────

#[test]
fn method_version_filtering() {
    let backend = create_test_backend();
    backend.set_php_version(PhpVersion::new(8, 4));

    let content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

class SplFixedArray {
    #[PhpStormStubsElementAvailable(from: '8.2')]
    public function __serialize(): array {}

    #[PhpStormStubsElementAvailable(from: '8.2')]
    public function __unserialize(array $data): void {}

    #[PhpStormStubsElementAvailable(to: '7.4')]
    public function legacyMethod(): void {}

    public function alwaysAvailable(): void {}
}
"#;

    let classes = Backend::parse_php_versioned(content, Some(PhpVersion::new(8, 4)));
    assert_eq!(classes.len(), 1);
    let method_names: Vec<&str> = classes[0].methods.iter().map(|m| m.name.as_str()).collect();

    // Should include __serialize, __unserialize, alwaysAvailable
    // Should exclude legacyMethod (to: 7.4)
    assert!(
        method_names.contains(&"__serialize"),
        "should include __serialize"
    );
    assert!(
        method_names.contains(&"__unserialize"),
        "should include __unserialize"
    );
    assert!(
        method_names.contains(&"alwaysAvailable"),
        "should include alwaysAvailable"
    );
    assert!(
        !method_names.contains(&"legacyMethod"),
        "should exclude legacyMethod"
    );
}

#[test]
fn method_version_filtering_picks_legacy() {
    let backend = create_test_backend();
    backend.set_php_version(PhpVersion::new(7, 4));

    let content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

class SplFixedArray {
    #[PhpStormStubsElementAvailable(from: '8.2')]
    public function __serialize(): array {}

    #[PhpStormStubsElementAvailable(to: '7.4')]
    public function legacyMethod(): void {}

    public function alwaysAvailable(): void {}
}
"#;

    let classes = Backend::parse_php_versioned(content, Some(PhpVersion::new(7, 4)));
    assert_eq!(classes.len(), 1);
    let method_names: Vec<&str> = classes[0].methods.iter().map(|m| m.name.as_str()).collect();

    assert!(
        !method_names.contains(&"__serialize"),
        "should exclude __serialize for 7.4"
    );
    assert!(
        method_names.contains(&"legacyMethod"),
        "should include legacyMethod for 7.4"
    );
    assert!(
        method_names.contains(&"alwaysAvailable"),
        "should include alwaysAvailable"
    );
}

// ─── No filtering without version ───────────────────────────────────────────

#[test]
fn no_version_includes_all_variants() {
    // When no PHP version is set (None), all variants should be included.
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

#[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')]
function my_func(): array|false {}

#[PhpStormStubsElementAvailable(from: '8.0')]
function my_func(): array {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, None);
    assert_eq!(
        functions.len(),
        2,
        "without version filtering, both variants should be present"
    );
}

// ─── Method parameter version filtering ─────────────────────────────────────

#[test]
fn method_parameter_version_filtering() {
    let content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

class FilesystemIterator {
    public function setFlags(
        #[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')] $flags = null,
        #[PhpStormStubsElementAvailable(from: '8.0')] int $flags
    ): void {}
}
"#;

    // PHP 8.4 — should get `int $flags`
    let classes = Backend::parse_php_versioned(content, Some(PhpVersion::new(8, 4)));
    let method = &classes[0].methods[0];
    assert_eq!(method.parameters.len(), 1);
    assert_eq!(method.parameters[0].name, "$flags");
    assert_eq!(method.parameters[0].type_hint_str().as_deref(), Some("int"));

    // PHP 7.4 — should get untyped `$flags = null`
    let classes = Backend::parse_php_versioned(content, Some(PhpVersion::new(7, 4)));
    let method = &classes[0].methods[0];
    assert_eq!(method.parameters.len(), 1);
    assert_eq!(method.parameters[0].name, "$flags");
    assert_eq!(method.parameters[0].type_hint, None);
}

// ─── Backend php_version accessor ───────────────────────────────────────────

#[test]
fn backend_default_version() {
    let backend = create_test_backend();
    assert_eq!(backend.php_version(), PhpVersion::new(8, 5));
}

#[test]
fn backend_set_version() {
    let backend = create_test_backend();
    backend.set_php_version(PhpVersion::new(8, 2));
    assert_eq!(backend.php_version(), PhpVersion::new(8, 2));
}

// ─── End-to-end: hover uses version filtering ───────────────────────────────

#[test]
fn hover_shows_version_filtered_function_signature() {
    // Simulate the array_map issue: with PHP 8.4, hover should show
    // `array $array` (not the untyped `$arrays` from 7.4)
    let backend = create_test_backend();
    backend.set_php_version(PhpVersion::new(8, 4));

    // Inject a versioned stub function
    let stub_content: &str = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable;

/**
 * Applies the callback to the elements of the given arrays
 * @link https://php.net/manual/en/function.array-map.php
 * @param callable|null $callback
 * @param array $array
 * @param array ...$arrays
 * @return array
 */
function array_map(
    ?callable $callback,
    #[PhpStormStubsElementAvailable(from: '8.0')] array $array,
    #[PhpStormStubsElementAvailable(from: '5.3', to: '7.4')] $arrays,
    array ...$arrays
): array {}
"#;

    // Manually inject the function into global_functions using versioned parsing
    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    {
        let mut fmap = backend.global_functions().write();
        for func in functions {
            fmap.insert(
                func.name.clone(),
                ("phpantom-stub-fn://array_map".to_string(), func),
            );
        }
    }

    let content = r#"<?php
array_map(null, []);
"#;
    let uri = "file:///test.php";

    let hover = hover_at(&backend, uri, content, 1, 2);
    if let Some(hover) = hover {
        let text = hover_text(&hover);
        // The signature should NOT contain the untyped `$arrays` parameter
        // that is only for PHP 5.3-7.4.
        assert!(
            !text.contains("$arrays, array ...$arrays"),
            "should not have both $arrays variants in: {}",
            text
        );
        // It should show `array $array` from the 8.0+ variant
        if text.contains("array_map") {
            assert!(
                text.contains("array $array"),
                "should show typed `array $array`: {}",
                text
            );
        }
    }
}

// ─── Aliased Attribute Names ────────────────────────────────────────────────

#[test]
fn element_available_alias_filters_parameters() {
    // intl/intl.php aliases PhpStormStubsElementAvailable as ElementAvailable.
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable as ElementAvailable;

function normalizer_normalize(
    string $string,
    #[ElementAvailable(from: '5.3', to: '5.6')] $form,
    #[ElementAvailable(from: '7.0')] int $form = 16,
    #[ElementAvailable(from: '5.3', to: '5.6')] $arg3
): string|false {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions.len(), 1);
    // On PHP 8.4, only the 7.0+ parameter variant should survive (plus $string).
    let params: Vec<&str> = functions[0]
        .parameters
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    assert_eq!(
        params,
        vec!["$string", "$form"],
        "old params should be filtered out"
    );
}

#[test]
fn element_available_alias_filters_parameters_legacy() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable as ElementAvailable;

function normalizer_normalize(
    string $string,
    #[ElementAvailable(from: '5.3', to: '5.6')] $form,
    #[ElementAvailable(from: '7.0')] int $form = 16,
    #[ElementAvailable(from: '5.3', to: '5.6')] $arg3
): string|false {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(5, 4)));
    assert_eq!(functions.len(), 1);
    let params: Vec<&str> = functions[0]
        .parameters
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    assert_eq!(
        params,
        vec!["$string", "$form", "$arg3"],
        "new param should be filtered out"
    );
}

#[test]
fn available_alias_filters_functions() {
    // ldap/ldap.php aliases PhpStormStubsElementAvailable as Available.
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable as Available;

#[Available(from: '8.0')]
function ldap_exop_refresh($ldap, string $dn, int $ttl): int|false {}

#[Available(from: '5.3', to: '7.4')]
function ldap_old_function(): bool {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions.len(), 1);
    assert_eq!(functions[0].name, "ldap_exop_refresh");
}

#[test]
fn available_alias_filters_parameters() {
    let backend = create_test_backend();

    let stub_content = r#"<?php
use JetBrains\PhpStorm\Internal\PhpStormStubsElementAvailable as Available;

function ldap_exop_passwd(
    $ldap,
    #[Available(from: '7.1', to: '7.1')] string $user = "",
    #[Available(from: '7.2', to: '7.2')] string $user,
    #[Available(from: '7.3')] string $user = "",
    #[Available(from: '7.3')] &$controls = null
): string|bool {}
"#;

    let functions = backend.parse_functions_versioned(stub_content, Some(PhpVersion::new(8, 0)));
    assert_eq!(functions.len(), 1);
    let params: Vec<&str> = functions[0]
        .parameters
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    assert_eq!(
        params,
        vec!["$ldap", "$user", "$controls"],
        "only 7.3+ params should survive"
    );
}

// ─── Display ────────────────────────────────────────────────────────────────

#[test]
fn php_version_display() {
    assert_eq!(PhpVersion::new(8, 4).to_string(), "8.4");
    assert_eq!(PhpVersion::new(7, 0).to_string(), "7.0");
}

// ─── LanguageLevelTypeAware — function return types ─────────────────────────

#[test]
fn language_level_function_return_type_selects_matching_version() {
    let backend = create_test_backend();

    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

#[LanguageLevelTypeAware(["8.0" => "int"], default: "int|false")]
function sleep(int $seconds): int|false {}
"#;

    // PHP 8.0+ should get "int"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 0)));
    assert_eq!(functions.len(), 1);
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int"),
        "PHP 8.0 should select the 8.0 variant"
    );

    // PHP 7.4 should get the default "int|false"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(7, 4)));
    assert_eq!(functions.len(), 1);
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int|false"),
        "PHP 7.4 should fall back to default"
    );
}

#[test]
fn language_level_function_return_type_multi_version() {
    let backend = create_test_backend();

    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

#[LanguageLevelTypeAware(['8.0' => 'int|false', '8.1' => 'int'], default: 'int')]
function bzerror(): int {}
"#;

    // PHP 8.1+ should get "int" (highest matching)
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int"),
        "PHP 8.4 should select 8.1 variant (highest <= target)"
    );

    // PHP 8.0 should get "int|false" (exact match for 8.0)
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 0)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int|false"),
        "PHP 8.0 should select the 8.0 variant"
    );

    // PHP 7.4 should get the default "int"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(7, 4)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int"),
        "PHP 7.4 should fall back to default"
    );
}

#[test]
fn language_level_function_return_type_empty_default() {
    let backend = create_test_backend();

    // Empty default means "no type" for older PHP versions.
    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

#[LanguageLevelTypeAware(['8.2' => 'true'], default: '')]
function phpinfo(int $flags = 0): bool {}
"#;

    // PHP 8.2+ should get "true"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 2)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("true"),
        "PHP 8.2 should select the 8.2 variant"
    );

    // PHP 8.1 should fall back to the native type since default is empty
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 1)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("bool"),
        "PHP 8.1 should fall back to native type when default is empty"
    );
}

#[test]
fn language_level_without_attribute_keeps_native_type() {
    let backend = create_test_backend();

    let stub = r#"<?php
function normal_function(string $arg): string {}
"#;

    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("string"),
        "Functions without LanguageLevelTypeAware keep native type"
    );
}

// ─── LanguageLevelTypeAware — parameter types ───────────────────────────────

#[test]
fn language_level_param_type_selects_matching_version() {
    let backend = create_test_backend();

    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

function pspell_check(
    #[LanguageLevelTypeAware(['8.1' => 'PSpell\Dictionary'], default: 'int')] $dictionary,
    string $word
): bool {}
"#;

    // PHP 8.1+ should get PSpell\Dictionary
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(functions[0].parameters.len(), 2);
    assert_eq!(
        functions[0].parameters[0].type_hint_str().as_deref(),
        Some("PSpell\\Dictionary"),
        "PHP 8.4 should select 8.1 variant for parameter"
    );

    // PHP 8.0 should get default "int"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 0)));
    assert_eq!(
        functions[0].parameters[0].type_hint_str().as_deref(),
        Some("int"),
        "PHP 8.0 should fall back to default for parameter"
    );
}

#[test]
fn language_level_param_empty_default_keeps_native_hint() {
    let backend = create_test_backend();

    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

function filter(
    $in,
    $out,
    &$consumed,
    #[LanguageLevelTypeAware(['8.0' => 'bool'], default: '')] $closing
): int {}
"#;

    // PHP 8.0+ should get "bool"
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 0)));
    assert_eq!(
        functions[0].parameters[3].type_hint_str().as_deref(),
        Some("bool"),
        "PHP 8.0 should select the 8.0 variant"
    );

    // PHP 7.4 — empty default means no type override; native hint is None
    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(7, 4)));
    assert_eq!(
        functions[0].parameters[3].type_hint_str().as_deref(),
        None,
        "PHP 7.4 should have no type when default is empty and native is untyped"
    );
}

// ─── LanguageLevelTypeAware — method return types ───────────────────────────

#[test]
fn language_level_method_return_type() {
    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

class SplFileObject {
    #[LanguageLevelTypeAware(['8.0' => 'string|false'], default: 'string')]
    public function fgets(): string {}
}
"#;

    let classes = Backend::parse_php_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(classes.len(), 1);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "fgets")
        .unwrap();
    assert_eq!(
        method.return_type_str().as_deref(),
        Some("string|false"),
        "PHP 8.4 should select the 8.0 variant for method return"
    );

    let classes = Backend::parse_php_versioned(stub, Some(PhpVersion::new(7, 4)));
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "fgets")
        .unwrap();
    assert_eq!(
        method.return_type_str().as_deref(),
        Some("string"),
        "PHP 7.4 should fall back to default for method return"
    );
}

// ─── LanguageLevelTypeAware — property types ────────────────────────────────

#[test]
fn language_level_property_type() {
    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

class php_user_filter {
    #[LanguageLevelTypeAware(['8.1' => 'string'], default: '')]
    public $filtername;

    #[LanguageLevelTypeAware(['8.1' => 'mixed'], default: '')]
    public $params;

    public $stream;
}
"#;

    // PHP 8.1+ should get the typed properties
    let classes = Backend::parse_php_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(classes.len(), 1);

    let filtername = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "filtername")
        .unwrap();
    assert_eq!(
        filtername.type_hint_str().as_deref(),
        Some("string"),
        "PHP 8.4 should select 8.1 type for $filtername"
    );

    let params = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "params")
        .unwrap();
    assert_eq!(
        params.type_hint_str().as_deref(),
        Some("mixed"),
        "PHP 8.4 should select 8.1 type for $params"
    );

    let stream = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "stream")
        .unwrap();
    assert_eq!(
        stream.type_hint_str().as_deref(),
        None,
        "$stream has no LanguageLevelTypeAware and no native type"
    );

    // PHP 7.4 — empty default means no type
    let classes = Backend::parse_php_versioned(stub, Some(PhpVersion::new(7, 4)));
    let filtername = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "filtername")
        .unwrap();
    assert_eq!(
        filtername.type_hint_str().as_deref(),
        None,
        "PHP 7.4 should have no type when default is empty"
    );
}

// ─── LanguageLevelTypeAware — no version (user code) ────────────────────────

#[test]
fn language_level_no_version_keeps_native_type() {
    let backend = create_test_backend();

    // When php_version is None (user code), LanguageLevelTypeAware is ignored
    // and the native type hint is preserved.
    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

#[LanguageLevelTypeAware(["8.0" => "int"], default: "int|false")]
function sleep(int $seconds): int|false {}
"#;

    let functions = backend.parse_functions_versioned(stub, None);
    assert_eq!(functions.len(), 1);
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("int|false"),
        "Without a target version, native type should be kept"
    );
}

// ─── LanguageLevelTypeAware — double-quoted strings ─────────────────────────

#[test]
fn language_level_double_quoted_strings() {
    let backend = create_test_backend();

    // Some stubs use double-quoted strings in the attribute.
    let stub = r#"<?php
use JetBrains\PhpStorm\Internal\LanguageLevelTypeAware;

#[LanguageLevelTypeAware(["8.0" => "string"], default: "string|false")]
function my_func(): string|false {}
"#;

    let functions = backend.parse_functions_versioned(stub, Some(PhpVersion::new(8, 4)));
    assert_eq!(
        functions[0].return_type_str().as_deref(),
        Some("string"),
        "Double-quoted strings in attribute should work"
    );
}