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
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
use crate::common::create_test_backend;
use phpantom_lsp::Visibility;

// ─── PHP Parsing / AST Extraction Tests ─────────────────────────────────────

#[tokio::test]
async fn test_parse_php_extracts_class_and_methods() {
    let backend = create_test_backend();
    let php = "<?php\nclass User {\n    function login() {}\n    function logout() {}\n}\n";

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "User");
    assert_eq!(classes[0].methods.len(), 2);
    assert_eq!(classes[0].methods[0].name, "login");
    assert_eq!(classes[0].methods[1].name, "logout");
}

#[tokio::test]
async fn test_parse_php_ignores_standalone_functions() {
    let backend = create_test_backend();
    let php = "<?php\nfunction standalone() {}\nclass Service {\n    function handle() {}\n}\n";

    let classes = backend.parse_php(php);
    assert_eq!(
        classes.len(),
        1,
        "Only class declarations should be extracted"
    );
    assert_eq!(classes[0].name, "Service");
    assert_eq!(classes[0].methods.len(), 1);
    assert_eq!(classes[0].methods[0].name, "handle");
}

#[tokio::test]
async fn test_parse_php_no_classes_returns_empty() {
    let backend = create_test_backend();
    let php = "<?php\nfunction foo() {}\n$x = 1;\n";

    let classes = backend.parse_php(php);
    assert!(classes.is_empty(), "No classes should be found");
}

#[tokio::test]
async fn test_parse_php_extracts_properties() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class User {\n",
        "    public string $name;\n",
        "    public int $age;\n",
        "    private $secret;\n",
        "    function login() {}\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(
        classes[0].properties.len(),
        3,
        "Should extract 3 properties"
    );

    let prop_names: Vec<&str> = classes[0]
        .properties
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    assert!(prop_names.contains(&"name"), "Should contain 'name'");
    assert!(prop_names.contains(&"age"), "Should contain 'age'");
    assert!(prop_names.contains(&"secret"), "Should contain 'secret'");

    // Verify type hints
    let name_prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "name")
        .unwrap();
    assert_eq!(
        name_prop.type_hint_str().as_deref(),
        Some("string"),
        "name property should have string type hint"
    );

    let age_prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "age")
        .unwrap();
    assert_eq!(
        age_prop.type_hint_str().as_deref(),
        Some("int"),
        "age property should have int type hint"
    );

    let secret_prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "secret")
        .unwrap();
    assert_eq!(
        secret_prop.type_hint, None,
        "secret property should have no type hint"
    );
}

#[tokio::test]
async fn test_parse_php_extracts_static_properties() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Counter {\n",
        "    public static int $count = 0;\n",
        "    public string $label;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].properties.len(), 2);

    let count_prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "count")
        .expect("Should have count property");
    assert!(count_prop.is_static, "count should be static");

    let label_prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "label")
        .expect("Should have label property");
    assert!(!label_prop.is_static, "label should not be static");
}

#[tokio::test]
async fn test_parse_php_extracts_method_return_type() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Greeter {\n",
        "    function greet(string $name): string {}\n",
        "    function doStuff() {}\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].methods.len(), 2);

    let greet = &classes[0].methods[0];
    assert_eq!(greet.name, "greet");
    assert_eq!(
        greet.return_type_str().as_deref(),
        Some("string"),
        "greet should have return type 'string'"
    );
    assert_eq!(greet.parameters.len(), 1);
    assert_eq!(greet.parameters[0].name, "$name");
    assert!(greet.parameters[0].is_required);
    assert_eq!(
        greet.parameters[0].type_hint_str().as_deref(),
        Some("string")
    );

    let do_stuff = &classes[0].methods[1];
    assert_eq!(do_stuff.name, "doStuff");
    assert_eq!(
        do_stuff.return_type, None,
        "doStuff should have no return type"
    );
}

#[tokio::test]
async fn test_parse_php_method_parameter_info() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Service {\n",
        "    function process(string $input, int $count, ?string $label = null, ...$extras): bool {}\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let method = &classes[0].methods[0];
    assert_eq!(method.name, "process");
    assert_eq!(method.parameters.len(), 4);

    let input = &method.parameters[0];
    assert_eq!(input.name, "$input");
    assert!(input.is_required);
    assert_eq!(input.type_hint_str().as_deref(), Some("string"));
    assert!(!input.is_variadic);

    let count = &method.parameters[1];
    assert_eq!(count.name, "$count");
    assert!(count.is_required);
    assert_eq!(count.type_hint_str().as_deref(), Some("int"));

    let label = &method.parameters[2];
    assert_eq!(label.name, "$label");
    assert!(
        !label.is_required,
        "$label has a default value, should not be required"
    );
    assert_eq!(label.type_hint_str().as_deref(), Some("?string"));

    let extras = &method.parameters[3];
    assert_eq!(extras.name, "$extras");
    assert!(
        !extras.is_required,
        "variadic params should not be required"
    );
    assert!(extras.is_variadic);
}

#[tokio::test]
async fn test_parse_php_property_with_default_value() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Settings {\n",
        "    public bool $debug = false;\n",
        "    public string $title = 'default';\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].properties.len(), 2);

    let prop_names: Vec<&str> = classes[0]
        .properties
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    assert!(prop_names.contains(&"debug"));
    assert!(prop_names.contains(&"title"));
}

#[tokio::test]
async fn test_parse_php_class_inside_implicit_namespace() {
    let backend = create_test_backend();
    let php = "<?php\nnamespace Demo;\n\nclass User {\n    function login() {}\n    function logout() {}\n}\n";

    let classes = backend.parse_php(php);
    assert_eq!(
        classes.len(),
        1,
        "Should find class inside implicit namespace"
    );
    assert_eq!(classes[0].name, "User");
    assert_eq!(classes[0].methods.len(), 2);
    assert_eq!(classes[0].methods[0].name, "login");
    assert_eq!(classes[0].methods[1].name, "logout");
}

#[tokio::test]
async fn test_parse_php_class_inside_brace_delimited_namespace() {
    let backend = create_test_backend();
    let php =
        "<?php\nnamespace Demo {\n    class Service {\n        function handle() {}\n    }\n}\n";

    let classes = backend.parse_php(php);
    assert_eq!(
        classes.len(),
        1,
        "Should find class inside brace-delimited namespace"
    );
    assert_eq!(classes[0].name, "Service");
    assert_eq!(classes[0].methods.len(), 1);
    assert_eq!(classes[0].methods[0].name, "handle");
}

#[tokio::test]
async fn test_parse_php_multiple_classes_in_brace_delimited_namespaces() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace Foo {\n",
        "    class A {\n",
        "        function doA() {}\n",
        "    }\n",
        "}\n",
        "namespace Bar {\n",
        "    class B {\n",
        "        function doB() {}\n",
        "    }\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 2, "Should find classes in both namespaces");
    assert_eq!(classes[0].name, "A");
    assert_eq!(classes[0].methods.len(), 1);
    assert_eq!(classes[0].methods[0].name, "doA");
    assert_eq!(classes[1].name, "B");
    assert_eq!(classes[1].methods.len(), 1);
    assert_eq!(classes[1].methods[0].name, "doB");
}

#[tokio::test]
async fn test_parse_php_static_method() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Factory {\n",
        "    public static function create(string $type): self {}\n",
        "    public function build(): void {}\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].methods.len(), 2);

    let create = &classes[0].methods[0];
    assert_eq!(create.name, "create");
    assert!(create.is_static, "create should be static");
    assert_eq!(create.parameters.len(), 1);
    assert_eq!(create.parameters[0].name, "$type");

    let build = &classes[0].methods[1];
    assert_eq!(build.name, "build");
    assert!(!build.is_static, "build should not be static");
}

#[tokio::test]
async fn test_parse_php_extracts_constants() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Config {\n",
        "    const VERSION = '1.0';\n",
        "    const int MAX_RETRIES = 3;\n",
        "    public string $name;\n",
        "    public function getName(): string {}\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].constants.len(), 2);

    let version = &classes[0].constants[0];
    assert_eq!(version.name, "VERSION");
    assert!(version.type_hint.is_none(), "VERSION has no type hint");

    let max_retries = &classes[0].constants[1];
    assert_eq!(max_retries.name, "MAX_RETRIES");
    assert_eq!(
        max_retries.type_hint_str().as_deref(),
        Some("int"),
        "MAX_RETRIES should have int type hint"
    );
}

#[tokio::test]
async fn test_parse_php_extracts_multiple_constants_in_one_declaration() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Status {\n",
        "    const ACTIVE = 1, INACTIVE = 0;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].constants.len(), 2);
    assert_eq!(classes[0].constants[0].name, "ACTIVE");
    assert_eq!(classes[0].constants[1].name, "INACTIVE");
}

#[tokio::test]
async fn test_parse_php_extracts_parent_class() {
    let backend = create_test_backend();
    let classes = backend.parse_php(concat!(
        "<?php\n",
        "class Animal {\n",
        "    public function breathe(): void {}\n",
        "}\n",
        "class Dog extends Animal {\n",
        "    public function bark(): void {}\n",
        "}\n",
    ));

    assert_eq!(classes.len(), 2);
    assert_eq!(classes[0].name, "Animal");
    assert!(classes[0].parent_class.is_none());
    assert_eq!(classes[1].name, "Dog");
    assert_eq!(classes[1].parent_class.as_deref(), Some("Animal"));
}

#[tokio::test]
async fn test_parse_php_extracts_visibility() {
    let backend = create_test_backend();
    let classes = backend.parse_php(concat!(
        "<?php\n",
        "class Foo {\n",
        "    public function pubMethod(): void {}\n",
        "    protected function protMethod(): void {}\n",
        "    private function privMethod(): void {}\n",
        "    function defaultMethod(): void {}\n",
        "    public string $pubProp;\n",
        "    protected string $protProp;\n",
        "    private string $privProp;\n",
        "    public const PUB_CONST = 1;\n",
        "    protected const PROT_CONST = 2;\n",
        "    private const PRIV_CONST = 3;\n",
        "    const DEFAULT_CONST = 4;\n",
        "}\n",
    ));

    assert_eq!(classes.len(), 1);
    let cls = &classes[0];

    // Methods
    let pub_m = cls.methods.iter().find(|m| m.name == "pubMethod").unwrap();
    assert_eq!(pub_m.visibility, Visibility::Public);
    let prot_m = cls.methods.iter().find(|m| m.name == "protMethod").unwrap();
    assert_eq!(prot_m.visibility, Visibility::Protected);
    let priv_m = cls.methods.iter().find(|m| m.name == "privMethod").unwrap();
    assert_eq!(priv_m.visibility, Visibility::Private);
    let def_m = cls
        .methods
        .iter()
        .find(|m| m.name == "defaultMethod")
        .unwrap();
    assert_eq!(
        def_m.visibility,
        Visibility::Public,
        "No modifier defaults to public"
    );

    // Properties
    let pub_p = cls.properties.iter().find(|p| p.name == "pubProp").unwrap();
    assert_eq!(pub_p.visibility, Visibility::Public);
    let prot_p = cls
        .properties
        .iter()
        .find(|p| p.name == "protProp")
        .unwrap();
    assert_eq!(prot_p.visibility, Visibility::Protected);
    let priv_p = cls
        .properties
        .iter()
        .find(|p| p.name == "privProp")
        .unwrap();
    assert_eq!(priv_p.visibility, Visibility::Private);

    // Constants
    let pub_c = cls
        .constants
        .iter()
        .find(|c| c.name == "PUB_CONST")
        .unwrap();
    assert_eq!(pub_c.visibility, Visibility::Public);
    let prot_c = cls
        .constants
        .iter()
        .find(|c| c.name == "PROT_CONST")
        .unwrap();
    assert_eq!(prot_c.visibility, Visibility::Protected);
    let priv_c = cls
        .constants
        .iter()
        .find(|c| c.name == "PRIV_CONST")
        .unwrap();
    assert_eq!(priv_c.visibility, Visibility::Private);
    let def_c = cls
        .constants
        .iter()
        .find(|c| c.name == "DEFAULT_CONST")
        .unwrap();
    assert_eq!(
        def_c.visibility,
        Visibility::Public,
        "No modifier defaults to public"
    );
}

// ─── Interface Parsing Tests ────────────────────────────────────────────────

#[tokio::test]
async fn test_parse_php_extracts_interface_methods() {
    let backend = create_test_backend();
    let php = r#"<?php
interface Loggable {
    public function log(string $message): void;
    public function getLogLevel(): int;
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Loggable");
    assert_eq!(classes[0].methods.len(), 2);
    assert_eq!(classes[0].methods[0].name, "log");
    assert_eq!(
        classes[0].methods[0].return_type_str().as_deref(),
        Some("void")
    );
    assert_eq!(classes[0].methods[1].name, "getLogLevel");
    assert_eq!(
        classes[0].methods[1].return_type_str().as_deref(),
        Some("int")
    );
}

#[tokio::test]
async fn test_parse_php_extracts_interface_constants() {
    let backend = create_test_backend();
    let php = r#"<?php
interface HasStatus {
    const STATUS_ACTIVE = 1;
    const STATUS_INACTIVE = 0;
    public function getStatus(): int;
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "HasStatus");
    assert_eq!(classes[0].constants.len(), 2);
    assert_eq!(classes[0].constants[0].name, "STATUS_ACTIVE");
    assert_eq!(classes[0].constants[1].name, "STATUS_INACTIVE");
    assert_eq!(classes[0].methods.len(), 1);
    assert_eq!(classes[0].methods[0].name, "getStatus");
}

#[tokio::test]
async fn test_parse_php_interface_extends() {
    let backend = create_test_backend();
    let php = r#"<?php
interface Readable {
    public function read(): string;
}
interface Writable extends Readable {
    public function write(string $data): void;
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 2);

    let readable = classes.iter().find(|c| c.name == "Readable").unwrap();
    assert!(readable.parent_class.is_none());
    assert_eq!(readable.methods.len(), 1);

    let writable = classes.iter().find(|c| c.name == "Writable").unwrap();
    assert_eq!(writable.parent_class.as_deref(), Some("Readable"));
    assert_eq!(writable.methods.len(), 1);
    assert_eq!(writable.methods[0].name, "write");
}

#[tokio::test]
async fn test_parse_php_interface_inside_namespace() {
    let backend = create_test_backend();
    let php = r#"<?php
namespace App\Contracts;

interface Repository {
    public function find(int $id): mixed;
    public function save(object $entity): void;
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Repository");
    assert_eq!(classes[0].methods.len(), 2);
    assert_eq!(classes[0].methods[0].name, "find");
    assert_eq!(classes[0].methods[1].name, "save");
}

#[tokio::test]
async fn test_parse_php_class_and_interface_together() {
    let backend = create_test_backend();
    let php = r#"<?php
interface Cacheable {
    public function getCacheKey(): string;
    const TTL = 3600;
}

class UserRepository implements Cacheable {
    public function getCacheKey(): string { return 'users'; }
    public function findAll(): array { return []; }
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 2);

    let iface = classes.iter().find(|c| c.name == "Cacheable").unwrap();
    assert_eq!(iface.methods.len(), 1);
    assert_eq!(iface.constants.len(), 1);
    assert_eq!(iface.constants[0].name, "TTL");

    let class = classes.iter().find(|c| c.name == "UserRepository").unwrap();
    assert_eq!(class.methods.len(), 2);
}

#[tokio::test]
async fn test_parse_php_interface_static_method() {
    let backend = create_test_backend();
    let php = r#"<?php
interface Factory {
    public static function create(): static;
    public function build(): object;
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Factory");
    assert_eq!(classes[0].methods.len(), 2);

    let create = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "create")
        .unwrap();
    assert!(create.is_static);
    assert_eq!(create.return_type_str().as_deref(), Some("static"));

    let build = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "build")
        .unwrap();
    assert!(!build.is_static);
}

// ─── Promoted Property Tests ────────────────────────────────────────────────

#[tokio::test]
async fn test_parse_php_promoted_properties_basic() {
    let backend = create_test_backend();
    let php = r#"<?php
class Service {
    public function __construct(
        private IShoppingCart $cart,
        protected Logger $logger,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    assert_eq!(
        cls.properties.len(),
        2,
        "Should extract 2 promoted properties"
    );

    let cart = cls.properties.iter().find(|p| p.name == "cart").unwrap();
    assert_eq!(cart.type_hint_str().as_deref(), Some("IShoppingCart"));
    assert_eq!(cart.visibility, Visibility::Private);
    assert!(!cart.is_static);

    let logger = cls.properties.iter().find(|p| p.name == "logger").unwrap();
    assert_eq!(logger.type_hint_str().as_deref(), Some("Logger"));
    assert_eq!(logger.visibility, Visibility::Protected);
    assert!(!logger.is_static);
}

#[tokio::test]
async fn test_parse_php_promoted_properties_mixed_with_regular() {
    let backend = create_test_backend();
    let php = r#"<?php
class ShoppingCartService {
    private IShoppingCart $regular;

    public function __construct(
        private IShoppingCart $promoted,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    assert_eq!(
        cls.properties.len(),
        2,
        "Should have regular + promoted property"
    );

    let regular = cls.properties.iter().find(|p| p.name == "regular").unwrap();
    assert_eq!(regular.type_hint_str().as_deref(), Some("IShoppingCart"));
    assert_eq!(regular.visibility, Visibility::Private);

    let promoted = cls
        .properties
        .iter()
        .find(|p| p.name == "promoted")
        .unwrap();
    assert_eq!(promoted.type_hint_str().as_deref(), Some("IShoppingCart"));
    assert_eq!(promoted.visibility, Visibility::Private);
}

#[tokio::test]
async fn test_parse_php_promoted_property_public_visibility() {
    let backend = create_test_backend();
    let php = r#"<?php
class Config {
    public function __construct(
        public string $name,
        public int $value,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    assert_eq!(cls.properties.len(), 2);

    for prop in &cls.properties {
        assert_eq!(prop.visibility, Visibility::Public);
    }

    let name = cls.properties.iter().find(|p| p.name == "name").unwrap();
    assert_eq!(name.type_hint_str().as_deref(), Some("string"));

    let value = cls.properties.iter().find(|p| p.name == "value").unwrap();
    assert_eq!(value.type_hint_str().as_deref(), Some("int"));
}

#[tokio::test]
async fn test_parse_php_non_promoted_constructor_params_ignored() {
    let backend = create_test_backend();
    let php = r#"<?php
class Service {
    public function __construct(
        private string $promoted,
        string $regularParam,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    assert_eq!(
        cls.properties.len(),
        1,
        "Only promoted params (with visibility) should become properties"
    );
    assert_eq!(cls.properties[0].name, "promoted");
}

#[tokio::test]
async fn test_parse_php_promoted_property_readonly() {
    let backend = create_test_backend();
    let php = r#"<?php
class User {
    public function __construct(
        public readonly string $name,
        private readonly int $id,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    assert_eq!(
        cls.properties.len(),
        2,
        "readonly promoted params are still promoted"
    );

    let name = cls.properties.iter().find(|p| p.name == "name").unwrap();
    assert_eq!(name.visibility, Visibility::Public);
    assert_eq!(name.type_hint_str().as_deref(), Some("string"));

    let id = cls.properties.iter().find(|p| p.name == "id").unwrap();
    assert_eq!(id.visibility, Visibility::Private);
    assert_eq!(id.type_hint_str().as_deref(), Some("int"));
}

// ─── Promoted Property @param Override Tests ────────────────────────────────

/// When a constructor docblock has `@param list<User> $users` and the native
/// hint is `array`, the promoted property should get `list<User>` as its type.
#[tokio::test]
async fn test_parse_promoted_property_param_docblock_override() {
    let backend = create_test_backend();
    let php = r#"<?php
class UserService {
    /**
     * @param list<User> $users
     * @param string $name
     */
    public function __construct(
        public array $users,
        public string $name,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    let users = cls.properties.iter().find(|p| p.name == "users").unwrap();
    assert_eq!(
        users.type_hint_str().as_deref(),
        Some("list<User>"),
        "@param list<User> should override native `array` for promoted property"
    );

    // `string` is a scalar — @param string should NOT override to a class name.
    // Both native and docblock agree, so the result stays `string`.
    let name = cls.properties.iter().find(|p| p.name == "name").unwrap();
    assert_eq!(
        name.type_hint_str().as_deref(),
        Some("string"),
        "Scalar @param string should keep native `string`"
    );
}

/// When the docblock provides a class type but the native hint is also a class,
/// the docblock should win (more specific).
#[tokio::test]
async fn test_parse_promoted_property_param_class_override() {
    let backend = create_test_backend();
    let php = r#"<?php
class Repository {
    /**
     * @param UserCollection $items
     */
    public function __construct(
        public object $items,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    let items = cls.properties.iter().find(|p| p.name == "items").unwrap();
    assert_eq!(
        items.type_hint_str().as_deref(),
        Some("UserCollection"),
        "@param UserCollection should override native `object` for promoted property"
    );
}

/// Without a docblock, promoted property should keep its native type as before.
#[tokio::test]
async fn test_parse_promoted_property_no_docblock_unchanged() {
    let backend = create_test_backend();
    let php = r#"<?php
class Service {
    public function __construct(
        public array $items,
        private string $name,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    let items = cls.properties.iter().find(|p| p.name == "items").unwrap();
    assert_eq!(items.type_hint_str().as_deref(), Some("array"));

    let name = cls.properties.iter().find(|p| p.name == "name").unwrap();
    assert_eq!(name.type_hint_str().as_deref(), Some("string"));
}

/// When the docblock has a `@param` for a non-promoted parameter, it should
/// not affect promoted properties that don't have their own `@param`.
#[tokio::test]
async fn test_parse_promoted_property_param_only_matching() {
    let backend = create_test_backend();
    let php = r#"<?php
class Service {
    /**
     * @param LoggerInterface $logger
     */
    public function __construct(
        public LoggerInterface $logger,
        public array $data,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    // $logger has matching @param — both agree on LoggerInterface
    let logger = cls.properties.iter().find(|p| p.name == "logger").unwrap();
    assert_eq!(logger.type_hint_str().as_deref(), Some("LoggerInterface"));

    // $data has no @param — should keep native `array`
    let data = cls.properties.iter().find(|p| p.name == "data").unwrap();
    assert_eq!(data.type_hint_str().as_deref(), Some("array"));
}

/// When a native hint is `int` (scalar) and @param says `UserId` (class),
/// `resolve_effective_type` should keep the native `int` because scalar
/// should not be overridden by a class name.
#[tokio::test]
async fn test_parse_promoted_property_param_scalar_not_overridden_by_class() {
    let backend = create_test_backend();
    let php = r#"<?php
class Service {
    /**
     * @param UserId $id
     */
    public function __construct(
        public int $id,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    let id = cls.properties.iter().find(|p| p.name == "id").unwrap();
    assert_eq!(
        id.type_hint_str().as_deref(),
        Some("int"),
        "Native scalar `int` should not be overridden by docblock class `UserId`"
    );
}

/// Generic Collection type in @param should override a plain `object` native hint.
#[tokio::test]
async fn test_parse_promoted_property_param_generic_override() {
    let backend = create_test_backend();
    let php = r#"<?php
class OrderService {
    /**
     * @param Collection<int, Order> $orders
     * @param array<string, mixed> $config
     */
    public function __construct(
        public object $orders,
        public array $config,
    ) {}
}
"#;

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);

    let cls = &classes[0];
    let orders = cls.properties.iter().find(|p| p.name == "orders").unwrap();
    assert_eq!(
        orders.type_hint_str().as_deref(),
        Some("Collection<int, Order>"),
        "@param Collection<int, Order> should override native `object`"
    );

    // array<string, mixed> — although the base is `array` (scalar), the
    // generic parameters carry useful type info for destructuring and
    // foreach, so resolve_effective_type now keeps the docblock type.
    let config = cls.properties.iter().find(|p| p.name == "config").unwrap();
    assert_eq!(
        config.type_hint_str().as_deref(),
        Some("array<string, mixed>"),
        "Docblock `array<string, mixed>` should override native `array` (generic params preserved)"
    );
}

// ─── Standalone Function Parsing Tests ──────────────────────────────────────

#[tokio::test]
async fn test_parse_functions_standalone() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "function hello(): void {}\n",
        "function add(int $a, int $b): int { return $a + $b; }\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 2, "Should extract 2 standalone functions");

    let hello = functions.iter().find(|f| f.name == "hello").unwrap();
    assert!(hello.parameters.is_empty());
    assert_eq!(hello.return_type_str().as_deref(), Some("void"));
    assert!(hello.namespace.is_none());

    let add = functions.iter().find(|f| f.name == "add").unwrap();
    assert_eq!(add.parameters.len(), 2);
    assert_eq!(add.parameters[0].name, "$a");
    assert_eq!(add.parameters[0].type_hint_str().as_deref(), Some("int"));
    assert_eq!(add.parameters[1].name, "$b");
    assert_eq!(add.return_type_str().as_deref(), Some("int"));
    assert!(add.namespace.is_none());
}

#[tokio::test]
async fn test_parse_functions_inside_namespace() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace Amp;\n",
        "\n",
        "function delay(float $seconds): void {}\n",
        "function async(callable $callback): void {}\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 2, "Should extract 2 namespaced functions");

    let delay = functions.iter().find(|f| f.name == "delay").unwrap();
    assert_eq!(delay.namespace.as_deref(), Some("Amp"));
    assert_eq!(delay.parameters.len(), 1);
    assert_eq!(delay.parameters[0].name, "$seconds");
    assert_eq!(
        delay.parameters[0].type_hint_str().as_deref(),
        Some("float")
    );
    assert_eq!(delay.return_type_str().as_deref(), Some("void"));

    let async_fn = functions.iter().find(|f| f.name == "async").unwrap();
    assert_eq!(async_fn.namespace.as_deref(), Some("Amp"));
}

#[tokio::test]
async fn test_parse_functions_ignores_class_methods() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "function standalone(): void {}\n",
        "class Service {\n",
        "    public function handle(): void {}\n",
        "}\n",
        "function another(): string { return ''; }\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(
        functions.len(),
        2,
        "Should only extract standalone functions, not class methods"
    );
    assert!(functions.iter().any(|f| f.name == "standalone"));
    assert!(functions.iter().any(|f| f.name == "another"));
    assert!(
        !functions.iter().any(|f| f.name == "handle"),
        "Class methods should not appear"
    );
}

#[tokio::test]
async fn test_parse_functions_no_return_type() {
    let backend = create_test_backend();
    let php = "<?php\nfunction legacy($x, $y) { return $x + $y; }\n";

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 1);

    let f = &functions[0];
    assert_eq!(f.name, "legacy");
    assert!(f.return_type.is_none(), "No return type hint");
    assert_eq!(f.parameters.len(), 2);
    assert!(f.parameters[0].type_hint.is_none());
}

#[tokio::test]
async fn test_parse_functions_nullable_and_union_types() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "function maybe(?string $val): ?int { return null; }\n",
        "function either(string|int $val): string|false { return ''; }\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 2);

    let maybe = functions.iter().find(|f| f.name == "maybe").unwrap();
    assert_eq!(
        maybe.parameters[0].type_hint_str().as_deref(),
        Some("?string")
    );
    assert_eq!(maybe.return_type_str().as_deref(), Some("?int"));

    let either = functions.iter().find(|f| f.name == "either").unwrap();
    assert_eq!(
        either.parameters[0].type_hint_str().as_deref(),
        Some("string|int")
    );
    assert_eq!(either.return_type_str().as_deref(), Some("string|false"));
}

#[tokio::test]
async fn test_parse_functions_variadic_and_reference() {
    let backend = create_test_backend();
    let php = "<?php\nfunction gather(string ...$items): array { return $items; }\nfunction swap(int &$a, int &$b): void {}\n";

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 2);

    let gather = functions.iter().find(|f| f.name == "gather").unwrap();
    assert_eq!(gather.parameters.len(), 1);
    assert!(gather.parameters[0].is_variadic);
    assert!(!gather.parameters[0].is_reference);
    assert!(!gather.parameters[0].is_required);

    let swap = functions.iter().find(|f| f.name == "swap").unwrap();
    assert_eq!(swap.parameters.len(), 2);
    assert!(swap.parameters[0].is_reference);
    assert!(!swap.parameters[0].is_variadic);
}

#[tokio::test]
async fn test_parse_functions_brace_delimited_namespace() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace Foo\\Bar {\n",
        "    function helper(): void {}\n",
        "}\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(functions.len(), 1);
    assert_eq!(functions[0].name, "helper");
    assert_eq!(functions[0].namespace.as_deref(), Some("Foo\\Bar"));
}

#[tokio::test]
async fn test_parse_functions_empty_file() {
    let backend = create_test_backend();
    let php = "<?php\n// nothing here\n";

    let functions = backend.parse_functions(php);
    assert!(functions.is_empty(), "No functions in an empty file");
}

// ─── Functions inside if-guards ─────────────────────────────────────────────

#[tokio::test]
async fn test_parse_functions_inside_function_exists_guard() {
    let backend = create_test_backend();
    // This is the exact pattern used by Laravel helpers.php and many other
    // PHP libraries: functions wrapped in `if (! function_exists(...))`.
    let php = concat!(
        "<?php\n",
        "\n",
        "if (! function_exists('session')) {\n",
        "    /**\n",
        "     * Get / set the specified session value.\n",
        "     */\n",
        "    function session($key = null, $default = null)\n",
        "    {\n",
        "        if (is_null($key)) {\n",
        "            return app('session');\n",
        "        }\n",
        "        return app('session')->get($key, $default);\n",
        "    }\n",
        "}\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(
        functions.len(),
        1,
        "Should find function inside if-guard block"
    );
    assert_eq!(functions[0].name, "session");
    assert_eq!(functions[0].parameters.len(), 2);
    assert!(
        functions[0].return_type.is_none(),
        "session() has no return type hint"
    );
}

#[tokio::test]
async fn test_parse_functions_multiple_function_exists_guards() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "\n",
        "if (! function_exists('app')) {\n",
        "    function app(?string $abstract = null, array $parameters = []): mixed\n",
        "    {\n",
        "        return Container::getInstance();\n",
        "    }\n",
        "}\n",
        "\n",
        "if (! function_exists('session')) {\n",
        "    function session($key = null, $default = null)\n",
        "    {\n",
        "        return app('session');\n",
        "    }\n",
        "}\n",
        "\n",
        "if (! function_exists('config')) {\n",
        "    function config($key = null, $default = null): mixed\n",
        "    {\n",
        "        return null;\n",
        "    }\n",
        "}\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(
        functions.len(),
        3,
        "Should find all 3 functions inside separate if-guards"
    );

    let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
    assert!(names.contains(&"app"), "Should find app()");
    assert!(names.contains(&"session"), "Should find session()");
    assert!(names.contains(&"config"), "Should find config()");

    let app = functions.iter().find(|f| f.name == "app").unwrap();
    assert_eq!(app.return_type_str().as_deref(), Some("mixed"));

    let config = functions.iter().find(|f| f.name == "config").unwrap();
    assert_eq!(config.return_type_str().as_deref(), Some("mixed"));
}

#[tokio::test]
async fn test_parse_functions_inside_namespace_with_function_exists_guard() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace Illuminate\\Support;\n",
        "\n",
        "if (! function_exists('Illuminate\\Support\\enum_value')) {\n",
        "    function enum_value($value): mixed\n",
        "    {\n",
        "        return $value;\n",
        "    }\n",
        "}\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(
        functions.len(),
        1,
        "Should find function inside if-guard within namespace"
    );
    assert_eq!(functions[0].name, "enum_value");
    assert_eq!(
        functions[0].namespace.as_deref(),
        Some("Illuminate\\Support"),
        "Should preserve namespace context"
    );
    assert_eq!(functions[0].return_type_str().as_deref(), Some("mixed"));
}

#[tokio::test]
async fn test_parse_functions_mixed_guarded_and_unguarded() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "\n",
        "function always_defined(): void {}\n",
        "\n",
        "if (! function_exists('maybe_defined')) {\n",
        "    function maybe_defined(): string { return ''; }\n",
        "}\n",
        "\n",
        "function also_always(): int { return 0; }\n",
    );

    let functions = backend.parse_functions(php);
    assert_eq!(
        functions.len(),
        3,
        "Should find both guarded and unguarded functions"
    );

    let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
    assert!(names.contains(&"always_defined"));
    assert!(names.contains(&"maybe_defined"));
    assert!(names.contains(&"also_always"));
}

// ─── Enum Parsing ───────────────────────────────────────────────────────────

#[tokio::test]
async fn test_parse_php_extracts_backed_enum_cases_as_constants() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum CustomerAvailabilityStatus: int\n",
        "{\n",
        "    case CUSTOMER_NOT_IN_AUDIENCE = -1;\n",
        "    case AVAILABLE_TO_CUSTOMER = 0;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1, "Should parse the enum as a class-like");
    assert_eq!(classes[0].name, "CustomerAvailabilityStatus");
    assert_eq!(
        classes[0].constants.len(),
        2,
        "Enum cases should be extracted as constants"
    );

    let case0 = &classes[0].constants[0];
    assert_eq!(case0.name, "CUSTOMER_NOT_IN_AUDIENCE");
    assert_eq!(
        case0.visibility,
        phpantom_lsp::types::Visibility::Public,
        "Enum cases are always public"
    );

    let case1 = &classes[0].constants[1];
    assert_eq!(case1.name, "AVAILABLE_TO_CUSTOMER");
}

#[tokio::test]
async fn test_parse_php_extracts_unit_enum_cases() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Color\n",
        "{\n",
        "    case Red;\n",
        "    case Green;\n",
        "    case Blue;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Color");
    assert_eq!(
        classes[0].constants.len(),
        3,
        "Unit enum cases should be extracted as constants"
    );

    let names: Vec<&str> = classes[0]
        .constants
        .iter()
        .map(|c| c.name.as_str())
        .collect();
    assert_eq!(names, vec!["Red", "Green", "Blue"]);
}

#[tokio::test]
async fn test_parse_php_extracts_enum_with_methods() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Suit: string\n",
        "{\n",
        "    case Hearts = 'H';\n",
        "    case Diamonds = 'D';\n",
        "    case Clubs = 'C';\n",
        "    case Spades = 'S';\n",
        "\n",
        "    public function color(): string\n",
        "    {\n",
        "        return match($this) {\n",
        "            Suit::Hearts, Suit::Diamonds => 'red',\n",
        "            Suit::Clubs, Suit::Spades => 'black',\n",
        "        };\n",
        "    }\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Suit");
    assert_eq!(classes[0].constants.len(), 4, "Should have 4 enum cases");
    assert_eq!(classes[0].methods.len(), 1, "Should have 1 method");
    assert_eq!(classes[0].methods[0].name, "color");
    assert_eq!(
        classes[0].methods[0].return_type_str().as_deref(),
        Some("string")
    );
}

#[tokio::test]
async fn test_parse_php_extracts_enum_with_constants_and_cases() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Status: int\n",
        "{\n",
        "    const DEFAULT_STATUS = 0;\n",
        "    case Active = 1;\n",
        "    case Inactive = 2;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Status");
    // Both the `const` and the `case` entries should appear as constants.
    assert_eq!(
        classes[0].constants.len(),
        3,
        "Should have 1 real constant + 2 enum cases"
    );

    let names: Vec<&str> = classes[0]
        .constants
        .iter()
        .map(|c| c.name.as_str())
        .collect();
    assert!(names.contains(&"DEFAULT_STATUS"));
    assert!(names.contains(&"Active"));
    assert!(names.contains(&"Inactive"));
}

#[tokio::test]
async fn test_parse_php_extracts_enum_inside_namespace() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace App\\Enums;\n",
        "\n",
        "enum Direction\n",
        "{\n",
        "    case Up;\n",
        "    case Down;\n",
        "    case Left;\n",
        "    case Right;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Direction");
    assert_eq!(classes[0].constants.len(), 4);
}

// ─── Implicit UnitEnum / BackedEnum interface tests ─────────────────────────

/// A unit enum (no backing type) should have `UnitEnum` in its `used_traits`.
#[tokio::test]
async fn test_parse_php_unit_enum_has_implicit_unit_enum_interface() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Color\n",
        "{\n",
        "    case Red;\n",
        "    case Green;\n",
        "    case Blue;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Color");
    // parse_php returns raw names before resolution; the leading backslash
    // marks the name as fully-qualified so resolve_name won't prepend a
    // namespace later.
    assert!(
        classes[0].used_traits.iter().any(|t| t == "\\UnitEnum"),
        "Unit enum should implicitly implement \\UnitEnum, got used_traits: {:?}",
        classes[0].used_traits
    );
    assert!(
        !classes[0].used_traits.iter().any(|t| t == "\\BackedEnum"),
        "Unit enum should NOT implement \\BackedEnum, got used_traits: {:?}",
        classes[0].used_traits
    );
}

/// A backed enum (`: int`) should have `BackedEnum` in its `used_traits`.
#[tokio::test]
async fn test_parse_php_backed_int_enum_has_implicit_backed_enum_interface() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Priority: int\n",
        "{\n",
        "    case Low = 0;\n",
        "    case High = 1;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Priority");
    assert!(
        classes[0].used_traits.iter().any(|t| t == "\\BackedEnum"),
        "Backed int enum should implicitly implement \\BackedEnum, got used_traits: {:?}",
        classes[0].used_traits
    );
    assert!(
        !classes[0].used_traits.iter().any(|t| t == "\\UnitEnum"),
        "Backed enum should NOT implement \\UnitEnum, got used_traits: {:?}",
        classes[0].used_traits
    );
}

/// A backed enum (`: string`) should have `BackedEnum` in its `used_traits`.
#[tokio::test]
async fn test_parse_php_backed_string_enum_has_implicit_backed_enum_interface() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "enum Suit: string\n",
        "{\n",
        "    case Hearts = 'H';\n",
        "    case Spades = 'S';\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Suit");
    assert!(
        classes[0].used_traits.iter().any(|t| t == "\\BackedEnum"),
        "Backed string enum should implicitly implement \\BackedEnum, got used_traits: {:?}",
        classes[0].used_traits
    );
}

/// An enum inside a namespace should still have UnitEnum/BackedEnum resolved
/// to the root namespace (not prefixed with the current namespace).
#[tokio::test]
async fn test_parse_php_namespaced_enum_implicit_interface_is_not_namespace_prefixed() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace App\\Enums;\n",
        "\n",
        "enum Mode\n",
        "{\n",
        "    case Automatic;\n",
        "    case Manual;\n",
        "}\n",
    );

    let mut classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert_eq!(classes[0].name, "Mode");
    // parse_php returns the raw `\UnitEnum` (leading backslash marks it as
    // fully-qualified in the PHP source).
    assert!(
        classes[0].used_traits.iter().any(|t| t == "\\UnitEnum"),
        "Namespaced unit enum should have \\UnitEnum before resolution, got: {:?}",
        classes[0].used_traits
    );

    // Simulate the resolution step that update_ast performs.
    let use_map = std::collections::HashMap::new();
    let namespace = Some("App\\Enums".to_string());
    phpantom_lsp::Backend::resolve_parent_class_names(&mut classes, &use_map, &namespace);

    // After resolution the leading backslash is stripped — the canonical
    // FQN representation never has a leading `\`.  The name must NOT be
    // namespace-prefixed (i.e. must remain `UnitEnum`, not
    // `App\Enums\UnitEnum`).
    assert!(
        classes[0].used_traits.iter().any(|t| t == "UnitEnum"),
        "After resolution, should be bare UnitEnum (canonical FQN), got: {:?}",
        classes[0].used_traits
    );
    assert!(
        !classes[0]
            .used_traits
            .iter()
            .any(|t| t == "App\\Enums\\UnitEnum"),
        "Should NOT be namespace-prefixed as App\\Enums\\UnitEnum, got: {:?}",
        classes[0].used_traits
    );
}

/// An enum that explicitly uses a trait should have both the trait and the
/// implicit interface in `used_traits`.
#[tokio::test]
async fn test_parse_php_enum_with_trait_also_has_implicit_interface() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "trait HasDescription {\n",
        "    public function describe(): string { return 'desc'; }\n",
        "}\n",
        "\n",
        "enum Status: int\n",
        "{\n",
        "    use HasDescription;\n",
        "\n",
        "    case Active = 1;\n",
        "    case Inactive = 0;\n",
        "}\n",
    );

    let classes = backend.parse_php(php);
    let enum_info = classes.iter().find(|c| c.name == "Status").unwrap();
    assert!(
        enum_info.used_traits.iter().any(|t| t == "HasDescription"),
        "Should include the explicit trait, got: {:?}",
        enum_info.used_traits
    );
    assert!(
        enum_info.used_traits.iter().any(|t| t == "\\BackedEnum"),
        "Should include implicit \\BackedEnum, got: {:?}",
        enum_info.used_traits
    );
}

// ─── parse_defines (AST-based) tests ────────────────────────────────────────

#[tokio::test]
async fn test_parse_defines_single_quoted() {
    let backend = create_test_backend();
    let defines = backend.parse_defines("<?php\ndefine('MY_CONST', 42);\n");
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["MY_CONST"]);
    // The offset should point to the `define` keyword on line 1.
    assert!(defines[0].1 > 0, "define keyword offset should be non-zero");
    // The value should be extracted from the second argument.
    assert_eq!(defines[0].2.as_deref(), Some("42"));
}

#[tokio::test]
async fn test_parse_defines_double_quoted() {
    let backend = create_test_backend();
    let defines = backend.parse_defines("<?php\ndefine(\"MY_CONST\", 'hello');\n");
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["MY_CONST"]);
}

#[tokio::test]
async fn test_parse_defines_multiple() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "define('PHP_EOL', \"\\n\");\n",
        "define('PHP_INT_MAX', 9223372036854775807);\n",
        "define('SORT_ASC', 4);\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["PHP_EOL", "PHP_INT_MAX", "SORT_ASC"]);
}

#[tokio::test]
async fn test_parse_defines_with_third_argument() {
    let backend = create_test_backend();
    let defines = backend.parse_defines("<?php\ndefine('__DIR__', '', true);\n");
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["__DIR__"]);
}

#[tokio::test]
async fn test_parse_defines_skips_non_define_calls() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "some_define('NOT_A_CONST', 1);\n",
        "user_define('ALSO_NOT', 2);\n",
        "define('REAL_CONST', 3);\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["REAL_CONST"]);
}

#[tokio::test]
async fn test_parse_defines_skips_dynamic_names() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "define($varName, 42);\n",
        "define('GOOD_CONST', 1);\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["GOOD_CONST"]);
}

#[tokio::test]
async fn test_parse_defines_empty_file() {
    let backend = create_test_backend();
    let defines = backend.parse_defines("<?php\n");
    assert!(defines.is_empty());
}

#[tokio::test]
async fn test_parse_defines_no_defines() {
    let backend = create_test_backend();
    let defines = backend.parse_defines("<?php\necho 'hello';\nfunction foo() {}\n");
    assert!(defines.is_empty());
}

#[tokio::test]
async fn test_parse_defines_inside_if_guard() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "if (!defined('MY_CONST')) {\n",
        "    define('MY_CONST', 'value');\n",
        "}\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["MY_CONST"]);
}

#[tokio::test]
async fn test_parse_defines_inside_namespace() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "namespace App;\n",
        "define('APP_VERSION', '2.0');\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["APP_VERSION"]);
}

#[tokio::test]
async fn test_parse_defines_inside_block() {
    let backend = create_test_backend();
    let content = concat!("<?php\n", "{\n", "    define('BLOCK_CONST', 1);\n", "}\n",);
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["BLOCK_CONST"]);
}

#[tokio::test]
async fn test_parse_defines_mixed_with_classes_and_functions() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "define('VERSION', '1.0');\n",
        "class Foo { public function bar() {} }\n",
        "define('DEBUG', true);\n",
        "function helper() {}\n",
        "define('MAX_RETRIES', 3);\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["VERSION", "DEBUG", "MAX_RETRIES"]);
}

#[tokio::test]
async fn test_parse_defines_ignores_method_calls_named_define() {
    let backend = create_test_backend();
    let content = concat!(
        "<?php\n",
        "$obj->define('NOT_A_CONST', 1);\n",
        "define('REAL_CONST', 2);\n",
    );
    let defines = backend.parse_defines(content);
    let names: Vec<&str> = defines.iter().map(|(n, _, _)| n.as_str()).collect();
    assert_eq!(names, vec!["REAL_CONST"]);
}

// ═══════════════════════════════════════════════════════════════════════════
// #[Deprecated] attribute extraction
// ═══════════════════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_deprecated_attribute_on_class_bare() {
    let backend = create_test_backend();
    let php = concat!("<?php\n", "#[Deprecated]\n", "class OldHelper {}\n",);
    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    assert!(
        classes[0].deprecation_message.is_some(),
        "Bare #[Deprecated] should set deprecation_message"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_class_with_reason_and_since() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[Deprecated(reason: 'Use NewApi instead', since: '8.2')]\n",
        "class OldApi {}\n",
    );
    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    let msg = classes[0].deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use NewApi instead"),
        "Expected reason in message, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 8.2"),
        "Expected since in message, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_class_positional_reason() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[Deprecated('Use NewHelper instead')]\n",
        "class OldHelper {}\n",
    );
    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    let msg = classes[0].deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use NewHelper instead"),
        "Expected positional reason in message, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_method_with_reason() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Mailer {\n",
        "    #[Deprecated(reason: 'Use sendAsync() instead', since: '8.1')]\n",
        "    public function sendLegacy(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    assert_eq!(classes.len(), 1);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "sendLegacy")
        .unwrap();
    let msg = method.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use sendAsync() instead"),
        "Expected reason in method deprecation, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 8.1"),
        "Expected since in method deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_method_bare() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Mailer {\n",
        "    #[Deprecated]\n",
        "    public function sendLegacy(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "sendLegacy")
        .unwrap();
    assert!(
        method.deprecation_message.is_some(),
        "Bare #[Deprecated] on method should set deprecation_message"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_property_with_reason() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Doc {\n",
        "    #[Deprecated('The property is deprecated', since: '8.4')]\n",
        "    public string $encoding = 'UTF-8';\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "encoding")
        .unwrap();
    let msg = prop.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("The property is deprecated"),
        "Expected reason in property deprecation, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 8.4"),
        "Expected since in property deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_property_bare() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Doc {\n",
        "    #[Deprecated]\n",
        "    public string $config = '';\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "config")
        .unwrap();
    assert!(
        prop.deprecation_message.is_some(),
        "Bare #[Deprecated] on property should set deprecation_message"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_constant() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class PDO {\n",
        "    #[Deprecated(reason: 'Use ATTR_EMULATE_PREPARES instead')]\n",
        "    const ATTR_OLD = 1;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let constant = classes[0]
        .constants
        .iter()
        .find(|c| c.name == "ATTR_OLD")
        .unwrap();
    let msg = constant.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use ATTR_EMULATE_PREPARES instead"),
        "Expected reason in constant deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_constant_bare() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Config {\n",
        "    #[Deprecated]\n",
        "    const OLD_MODE = 0;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let constant = classes[0]
        .constants
        .iter()
        .find(|c| c.name == "OLD_MODE")
        .unwrap();
    assert!(
        constant.deprecation_message.is_some(),
        "Bare #[Deprecated] on constant should set deprecation_message"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_function() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[Deprecated(reason: 'Use new_helper() instead', since: '7.4')]\n",
        "function old_helper(): void {}\n",
    );
    let functions = backend.parse_functions(php);
    let func = functions.iter().find(|f| f.name == "old_helper").unwrap();
    let msg = func.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use new_helper() instead"),
        "Expected reason in function deprecation, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 7.4"),
        "Expected since in function deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_function_bare() {
    let backend = create_test_backend();
    let php = concat!("<?php\n", "#[Deprecated]\n", "function old_fn(): void {}\n",);
    let functions = backend.parse_functions(php);
    let func = functions.iter().find(|f| f.name == "old_fn").unwrap();
    assert!(
        func.deprecation_message.is_some(),
        "Bare #[Deprecated] on function should set deprecation_message"
    );
}

#[tokio::test]
async fn test_docblock_deprecated_takes_priority_over_attribute() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Mailer {\n",
        "    /**\n",
        "     * @deprecated Use sendModern() instead.\n",
        "     */\n",
        "    #[Deprecated(reason: 'Attribute message')]\n",
        "    public function sendLegacy(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "sendLegacy")
        .unwrap();
    let msg = method.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use sendModern() instead"),
        "Docblock @deprecated should take priority, got: {msg}"
    );
    assert!(
        !msg.contains("Attribute message"),
        "Attribute message should not appear when docblock has @deprecated, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_since_only() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Config {\n",
        "    #[Deprecated(since: '7.4')]\n",
        "    const OLD_MODE = 0;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let constant = classes[0]
        .constants
        .iter()
        .find(|c| c.name == "OLD_MODE")
        .unwrap();
    let msg = constant.deprecation_message.as_deref().unwrap();
    assert_eq!(msg, "since PHP 7.4");
}

#[tokio::test]
async fn test_deprecated_attribute_on_interface() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[Deprecated(reason: 'Use NewInterface instead')]\n",
        "interface OldInterface {\n",
        "    public function doThing(): void;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let iface = classes.iter().find(|c| c.name == "OldInterface").unwrap();
    let msg = iface.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use NewInterface instead"),
        "Expected reason in interface deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_on_enum() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[Deprecated(reason: 'Use StatusV2 instead')]\n",
        "enum Status {\n",
        "    case Active;\n",
        "    case Inactive;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let enm = classes.iter().find(|c| c.name == "Status").unwrap();
    let msg = enm.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use StatusV2 instead"),
        "Expected reason in enum deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_non_deprecated_elements_unaffected() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Service {\n",
        "    public function handle(): void {}\n",
        "    public string $name = '';\n",
        "    const VERSION = 1;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "handle")
        .unwrap();
    assert!(method.deprecation_message.is_none());
    let prop = classes[0]
        .properties
        .iter()
        .find(|p| p.name == "name")
        .unwrap();
    assert!(prop.deprecation_message.is_none());
    let constant = classes[0]
        .constants
        .iter()
        .find(|c| c.name == "VERSION")
        .unwrap();
    assert!(constant.deprecation_message.is_none());
}

#[tokio::test]
async fn test_deprecated_attribute_native_php84_message_named_arg() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[\\Deprecated(message: 'Use safe_replacement() instead', since: '1.5')]\n",
        "function unsafe_function(): void {}\n",
    );
    let functions = backend.parse_functions(php);
    let func = functions
        .iter()
        .find(|f| f.name == "unsafe_function")
        .unwrap();
    let msg = func.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use safe_replacement() instead"),
        "Expected message in function deprecation, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 1.5"),
        "Expected since in function deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_native_php84_fqn_on_method() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Service {\n",
        "    #[\\Deprecated(message: 'Use processV2() instead', since: '8.4')]\n",
        "    public function process(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "process")
        .unwrap();
    let msg = method.deprecation_message.as_deref().unwrap();
    assert!(
        msg.contains("Use processV2() instead"),
        "Expected message in method deprecation, got: {msg}"
    );
    assert!(
        msg.contains("since PHP 8.4"),
        "Expected since in method deprecation, got: {msg}"
    );
}

#[tokio::test]
async fn test_deprecated_attribute_native_php84_message_only() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Config {\n",
        "    #[\\Deprecated(message: 'Use NEW_LIMIT instead')]\n",
        "    const OLD_LIMIT = 100;\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let constant = classes[0]
        .constants
        .iter()
        .find(|c| c.name == "OLD_LIMIT")
        .unwrap();
    let msg = constant.deprecation_message.as_deref().unwrap();
    assert_eq!(msg, "Use NEW_LIMIT instead");
}

#[tokio::test]
async fn test_deprecated_attribute_fqn_without_backslash_prefix() {
    // JetBrains stubs use `#[Deprecated]` (short name via use import).
    // Native PHP 8.4 uses `#[\Deprecated]` (FQN with leading backslash).
    // Both should work identically.
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Demo {\n",
        "    #[Deprecated(reason: 'JetBrains style')]\n",
        "    public function jetbrainsStyle(): void {}\n",
        "\n",
        "    #[\\Deprecated(message: 'Native PHP style')]\n",
        "    public function nativeStyle(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let jb = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "jetbrainsStyle")
        .unwrap();
    assert!(
        jb.deprecation_message
            .as_deref()
            .unwrap()
            .contains("JetBrains style"),
        "JetBrains-style #[Deprecated(reason:)] should work"
    );
    let native = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "nativeStyle")
        .unwrap();
    assert!(
        native
            .deprecation_message
            .as_deref()
            .unwrap()
            .contains("Native PHP style"),
        "Native-style #[\\Deprecated(message:)] should work"
    );
}

#[tokio::test]
async fn test_custom_namespaced_deprecated_attribute_does_not_trigger() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "namespace App;\n",
        "\n",
        "#[\\Test\\Deprecated(reason: 'Not a real deprecation')]\n",
        "function still_fine(): void {}\n",
    );
    let functions = backend.parse_functions(php);
    let func = functions.iter().find(|f| f.name == "still_fine").unwrap();
    assert!(
        func.deprecation_message.is_none(),
        "#[\\Test\\Deprecated] should NOT trigger deprecation, got: {:?}",
        func.deprecation_message
    );
}

#[tokio::test]
async fn test_custom_namespaced_deprecated_attribute_on_method_does_not_trigger() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "class Service {\n",
        "    #[\\App\\Attributes\\Deprecated(reason: 'Custom attribute')]\n",
        "    public function process(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let method = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "process")
        .unwrap();
    assert!(
        method.deprecation_message.is_none(),
        "#[\\App\\Attributes\\Deprecated] should NOT trigger deprecation, got: {:?}",
        method.deprecation_message
    );
}

#[tokio::test]
async fn test_custom_namespaced_deprecated_attribute_on_class_does_not_trigger() {
    let backend = create_test_backend();
    let php = concat!(
        "<?php\n",
        "#[\\Vendor\\Deprecated]\n",
        "class OldService {}\n",
    );
    let classes = backend.parse_php(php);
    assert!(
        classes[0].deprecation_message.is_none(),
        "#[\\Vendor\\Deprecated] should NOT trigger class deprecation, got: {:?}",
        classes[0].deprecation_message
    );
}

#[tokio::test]
async fn test_legitimate_deprecated_attributes_still_work() {
    let backend = create_test_backend();
    // Verify \Deprecated and \JetBrains\PhpStorm\Deprecated still match.
    let php = concat!(
        "<?php\n",
        "class Demo {\n",
        "    #[\\Deprecated(message: 'native')]\n",
        "    public function nativeAttr(): void {}\n",
        "\n",
        "    #[\\JetBrains\\PhpStorm\\Deprecated(reason: 'jetbrains')]\n",
        "    public function jbAttr(): void {}\n",
        "}\n",
    );
    let classes = backend.parse_php(php);
    let native = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "nativeAttr")
        .unwrap();
    assert!(
        native.deprecation_message.is_some(),
        "#[\\Deprecated] should trigger deprecation"
    );
    let jb = classes[0]
        .methods
        .iter()
        .find(|m| m.name == "jbAttr")
        .unwrap();
    assert!(
        jb.deprecation_message.is_some(),
        "#[\\JetBrains\\PhpStorm\\Deprecated] should trigger deprecation"
    );
}