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
//! "Generate property hooks" code action (PHP 8.4+).
//!
//! When the cursor is on a property declaration inside a class-like body,
//! this module offers up to three code actions:
//!
//! 1. **Generate get hook** — adds a `get` hook to the property.
//! 2. **Generate set hook** — adds a `set` hook to the property.
//! 3. **Generate get and set hooks** — adds both hooks.
//!
//! **Code action kind:** `refactor`.
//!
//! - **Static properties** are skipped (PHP 8.4 does not support hooks on
//!   static properties).
//! - **Readonly properties** only get the "Generate get hook" action.
//! - **Interface / abstract class properties** generate abstract hook
//!   signatures (no body).
//! - **Properties that already have hooks** only offer the missing hook(s).
//! - **Default values** are preserved when rewriting.
//! - **Constructor-promoted properties** are supported.

use std::collections::HashMap;

use bumpalo::Bump;
use mago_span::HasSpan;
use mago_syntax::ast::class_like::property::Property;
use mago_syntax::ast::modifier::Modifier;
use tower_lsp::lsp_types::*;

use super::cursor_context::{
    ClassLikeContextKind, CursorContext, MemberContext, find_cursor_context,
};
use super::detect_indent_from_members;
use crate::Backend;
use crate::util::offset_to_position;

// ── Data types ──────────────────────────────────────────────────────────────

/// Describes a property for which hooks can be generated.
struct HookableProperty {
    /// Property name without the `$` prefix.
    name: String,
}

// ── Which hooks already exist ───────────────────────────────────────────────

/// Check which hook names already exist on a hooked property.
fn existing_hook_names<'a>(property: &Property<'a>) -> (bool, bool) {
    match property {
        Property::Hooked(hooked) => {
            let mut has_get = false;
            let mut has_set = false;
            for hook in hooked.hook_list.hooks.iter() {
                match hook.name.value {
                    "get" => has_get = true,
                    "set" => has_set = true,
                    _ => {}
                }
            }
            (has_get, has_set)
        }
        Property::Plain(_) => (false, false),
    }
}

/// Check if the modifier list includes `readonly`.
fn has_readonly<'a>(modifiers: impl Iterator<Item = &'a Modifier<'a>>) -> bool {
    modifiers
        .into_iter()
        .any(|m| matches!(m, Modifier::Readonly(_)))
}

/// Check if the modifier list includes `static`.
fn has_static<'a>(modifiers: impl Iterator<Item = &'a Modifier<'a>>) -> bool {
    modifiers.into_iter().any(|m| m.is_static())
}

// ── Hook text generation ────────────────────────────────────────────────────

/// Build the replacement text for a property declaration with hooks.
///
/// This replaces the entire property declaration (from its start to its
/// end) with a new declaration that includes the requested hooks.
fn build_hooked_property_text(
    prop: &HookableProperty,
    original_text: &str,
    indent: &str,
    gen_get: bool,
    gen_set: bool,
    is_interface: bool,
    existing_hooks_text: Option<&str>,
) -> String {
    // For a plain property, we rewrite the whole declaration.
    // For a hooked property, we insert into the existing hook block.
    //
    // The approach for plain properties:
    //   Strip the trailing semicolon and add a hook block.
    //
    // The approach for hooked properties (adding missing hook):
    //   Insert the new hook(s) before the closing brace.

    let mut result = String::new();

    if let Some(existing) = existing_hooks_text {
        // We're adding hooks to an already-hooked property.
        // `existing` is the full property text including the hook block.
        // We need to insert the new hook(s) before the closing `}`.
        let trimmed = existing.trim_end();
        let close_brace_pos = trimmed.rfind('}');
        if let Some(pos) = close_brace_pos {
            result.push_str(&trimmed[..pos]);
            // Add the new hooks.
            if gen_get {
                result.push_str(&build_single_hook("get", prop, indent, is_interface));
            }
            if gen_set {
                result.push_str(&build_single_hook("set", prop, indent, is_interface));
            }
            result.push_str(indent);
            result.push('}');
        }
    } else {
        // Plain property: strip the semicolon, add the hook block.
        let trimmed = original_text.trim_end();
        let base = if let Some(stripped) = trimmed.strip_suffix(';') {
            stripped.trim_end()
        } else {
            trimmed
        };
        result.push_str(base);
        result.push_str(" {\n");

        if gen_get {
            result.push_str(&build_single_hook("get", prop, indent, is_interface));
        }
        if gen_set {
            result.push_str(&build_single_hook("set", prop, indent, is_interface));
        }

        result.push_str(indent);
        result.push('}');
    }

    result
}

/// Build a single hook body (`get` or `set`).
fn build_single_hook(
    kind: &str,
    prop: &HookableProperty,
    indent: &str,
    is_interface: bool,
) -> String {
    let mut s = String::new();
    let hook_indent = format!(
        "{indent}{indent_unit}",
        indent_unit = detect_indent_unit(indent)
    );

    if is_interface {
        // Abstract hook: just the signature with a semicolon.
        s.push_str(&hook_indent);
        s.push_str(kind);
        s.push_str(";\n");
    } else {
        // Concrete hook with arrow expression.
        s.push_str(&hook_indent);
        s.push_str(kind);
        s.push_str(" => ");
        match kind {
            "get" => {
                s.push_str("$this->");
                s.push_str(&prop.name);
                s.push_str(";\n");
            }
            "set" => {
                s.push_str("$this->");
                s.push_str(&prop.name);
                s.push_str(" = $value;\n");
            }
            _ => {}
        }
    }

    s
}

/// Detect the indent unit from the member indent string.
///
/// If the indent is tabs, return a single tab.  Otherwise return four
/// spaces (matching the most common convention).
fn detect_indent_unit(indent: &str) -> &str {
    if indent.contains('\t') { "\t" } else { "    " }
}

// ── Public API ──────────────────────────────────────────────────────────────

impl Backend {
    /// Collect "Generate get hook", "Generate set hook", and
    /// "Generate get and set hooks" code actions for the cursor position.
    pub(crate) fn collect_generate_property_hook_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        let doc_uri: Url = match uri.parse() {
            Ok(u) => u,
            Err(_) => return,
        };

        let cursor_offset = crate::util::position_to_offset(content, params.range.start);

        let arena = Bump::new();
        let file_id = mago_database::file::FileId::new("input.php");
        let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

        let ctx = find_cursor_context(&program.statements, cursor_offset);

        let (property, all_members, class_kind, class_readonly) = match &ctx {
            CursorContext::InClassLike {
                kind,
                class_readonly,
                member: MemberContext::Property(prop),
                all_members,
            } => (*prop, *all_members, *kind, *class_readonly),
            _ => return,
        };

        // Enums cannot have properties (only backed enum cases), and
        // PHP 8.4 does not support hooks on enum properties anyway.
        if class_kind == ClassLikeContextKind::Enum {
            return;
        }

        let is_interface = class_kind == ClassLikeContextKind::Interface;

        // Check for static — hooks are not supported on static properties.
        let is_static = match property {
            Property::Plain(plain) => has_static(plain.modifiers.iter()),
            Property::Hooked(hooked) => has_static(hooked.modifiers.iter()),
        };
        if is_static {
            return;
        }

        let prop_readonly = match property {
            Property::Plain(plain) => has_readonly(plain.modifiers.iter()),
            Property::Hooked(hooked) => has_readonly(hooked.modifiers.iter()),
        };
        let is_readonly = prop_readonly || class_readonly;

        // PHP 8.4 does not allow hooks on readonly properties at all.
        // A `readonly class` makes every property readonly implicitly.
        if is_readonly {
            return;
        }

        // Get the property name.
        let prop_name = match property {
            Property::Plain(plain) => {
                // For multi-variable declarations like `public int $a, $b;`,
                // use the first variable name. Multi-variable declarations
                // can't have hooks anyway.
                if let Some(first_item) = plain.items.first() {
                    let var = first_item.variable();
                    var.name.strip_prefix('$').unwrap_or(var.name).to_string()
                } else {
                    return;
                }
            }
            Property::Hooked(hooked) => {
                let var = hooked.item.variable();
                var.name.strip_prefix('$').unwrap_or(var.name).to_string()
            }
        };

        // For plain properties with multiple variables, hooks cannot be
        // generated (PHP does not support hooks on multi-variable
        // declarations).
        if let Property::Plain(plain) = property
            && plain.items.len() > 1
        {
            return;
        }

        // Check which hooks already exist.
        let (has_get, has_set) = existing_hook_names(property);

        let can_get = !has_get;
        let can_set = !has_set;

        if !can_get && !can_set {
            return;
        }

        let prop_info = HookableProperty { name: prop_name };

        let indent = detect_indent_from_members(all_members, content);

        // Get the property's full span so we can replace it.
        let prop_span = property.span();
        let prop_start = prop_span.start.offset as usize;
        let prop_end = prop_span.end.offset as usize;

        let original_text = &content[prop_start..prop_end];

        let start_pos = offset_to_position(content, prop_start);
        let end_pos = offset_to_position(content, prop_end);
        let replace_range = Range {
            start: start_pos,
            end: end_pos,
        };

        let existing_hooks_text = match property {
            Property::Hooked(_) => Some(original_text),
            Property::Plain(_) => None,
        };

        // ── Generate get hook ───────────────────────────────────────────
        if can_get {
            let new_text = build_hooked_property_text(
                &prop_info,
                original_text,
                &indent,
                true,
                false,
                is_interface,
                existing_hooks_text,
            );

            let edit = TextEdit {
                range: replace_range,
                new_text,
            };

            let mut changes = HashMap::new();
            changes.insert(doc_uri.clone(), vec![edit]);

            out.push(CodeActionOrCommand::CodeAction(CodeAction {
                title: "Generate get hook".to_string(),
                kind: Some(CodeActionKind::REFACTOR),
                diagnostics: None,
                edit: Some(WorkspaceEdit {
                    changes: Some(changes),
                    document_changes: None,
                    change_annotations: None,
                }),
                command: None,
                is_preferred: Some(false),
                disabled: None,
                data: None,
            }));
        }

        // ── Generate set hook ───────────────────────────────────────────
        if can_set {
            let new_text = build_hooked_property_text(
                &prop_info,
                original_text,
                &indent,
                false,
                true,
                is_interface,
                existing_hooks_text,
            );

            let edit = TextEdit {
                range: replace_range,
                new_text,
            };

            let mut changes = HashMap::new();
            changes.insert(doc_uri.clone(), vec![edit]);

            out.push(CodeActionOrCommand::CodeAction(CodeAction {
                title: "Generate set hook".to_string(),
                kind: Some(CodeActionKind::REFACTOR),
                diagnostics: None,
                edit: Some(WorkspaceEdit {
                    changes: Some(changes),
                    document_changes: None,
                    change_annotations: None,
                }),
                command: None,
                is_preferred: Some(false),
                disabled: None,
                data: None,
            }));
        }

        // ── Generate get and set hooks ──────────────────────────────────
        if can_get && can_set {
            let new_text = build_hooked_property_text(
                &prop_info,
                original_text,
                &indent,
                true,
                true,
                is_interface,
                existing_hooks_text,
            );

            let edit = TextEdit {
                range: replace_range,
                new_text,
            };

            let mut changes = HashMap::new();
            changes.insert(doc_uri, vec![edit]);

            out.push(CodeActionOrCommand::CodeAction(CodeAction {
                title: "Generate get and set hooks".to_string(),
                kind: Some(CodeActionKind::REFACTOR),
                diagnostics: None,
                edit: Some(WorkspaceEdit {
                    changes: Some(changes),
                    document_changes: None,
                    change_annotations: None,
                }),
                command: None,
                is_preferred: Some(false),
                disabled: None,
                data: None,
            }));
        }
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── Unit tests for hook text builders ────────────────────────────────

    fn make_prop(name: &str) -> HookableProperty {
        HookableProperty {
            name: name.to_string(),
        }
    }

    #[test]
    fn builds_get_hook_for_plain_property() {
        let prop = make_prop("name");
        let original = "public string $name;";
        let result = build_hooked_property_text(&prop, original, "    ", true, false, false, None);
        assert!(result.contains("get => $this->name;"), "got: {result}");
        assert!(!result.contains("set"), "got: {result}");
        assert!(result.starts_with("public string $name {"), "got: {result}");
        assert!(result.ends_with('}'), "got: {result}");
    }

    #[test]
    fn builds_set_hook_for_plain_property() {
        let prop = make_prop("name");
        let original = "public string $name;";
        let result = build_hooked_property_text(&prop, original, "    ", false, true, false, None);
        assert!(
            result.contains("set => $this->name = $value;"),
            "got: {result}"
        );
        assert!(!result.contains("get"), "got: {result}");
    }

    #[test]
    fn builds_both_hooks_for_plain_property() {
        let prop = make_prop("name");
        let original = "public string $name;";
        let result = build_hooked_property_text(&prop, original, "    ", true, true, false, None);
        assert!(result.contains("get => $this->name;"), "got: {result}");
        assert!(
            result.contains("set => $this->name = $value;"),
            "got: {result}"
        );
    }

    #[test]
    fn builds_abstract_hooks_for_interface() {
        let prop = make_prop("name");
        let original = "public string $name;";
        let result = build_hooked_property_text(&prop, original, "    ", true, true, true, None);
        assert!(result.contains("get;"), "got: {result}");
        assert!(result.contains("set;"), "got: {result}");
        assert!(!result.contains("=>"), "got: {result}");
    }

    #[test]
    fn preserves_default_value() {
        let prop = make_prop("name");
        let original = "public string $name = 'default';";
        let result = build_hooked_property_text(&prop, original, "    ", true, false, false, None);
        assert!(
            result.contains("$name = 'default'"),
            "default value should be preserved, got: {result}"
        );
        assert!(result.contains("get => $this->name;"), "got: {result}");
    }

    #[test]
    fn adds_hook_to_existing_hooked_property() {
        let prop = make_prop("name");
        let existing = "public string $name {\n        get => $this->name;\n    }";
        let result =
            build_hooked_property_text(&prop, existing, "    ", false, true, false, Some(existing));
        assert!(result.contains("get => $this->name;"), "got: {result}");
        assert!(
            result.contains("set => $this->name = $value;"),
            "got: {result}"
        );
    }

    #[test]
    fn tab_indentation() {
        let prop = make_prop("name");
        let original = "public string $name;";
        let result = build_hooked_property_text(&prop, original, "\t", true, false, false, None);
        assert!(result.contains("\t\tget =>"), "got: {result}");
    }

    #[test]
    fn detect_indent_unit_spaces() {
        assert_eq!(detect_indent_unit("    "), "    ");
    }

    #[test]
    fn detect_indent_unit_tabs() {
        assert_eq!(detect_indent_unit("\t"), "\t");
    }

    // ── Integration: code action on Backend ─────────────────────────────

    #[test]
    fn offers_all_three_actions_for_plain_property() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            3,
            "Expected 3 hook actions, got: {:?}",
            hook_actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn readonly_property_offers_no_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public readonly string $name;\n}";

        let pos = content.find("public readonly").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            0,
            "readonly properties cannot have hooks in PHP 8.4"
        );
    }

    #[test]
    fn static_property_offers_no_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public static string $name;\n}";

        let pos = content.find("public static").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            0,
            "static properties should not offer hook actions"
        );
    }

    #[test]
    fn interface_property_generates_abstract_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\ninterface Foo {\n    public string $name { get; }\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        // The property already has `get;` so only `set` should be offered.
        assert_eq!(
            hook_actions.len(),
            1,
            "interface with existing get hook should only offer set, got: {:?}",
            hook_actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );

        if let CodeActionOrCommand::CodeAction(ca) = &hook_actions[0] {
            assert_eq!(ca.title, "Generate set hook");
            // Verify the generated text uses abstract hook syntax.
            if let Some(ref edit) = ca.edit
                && let Some(ref changes) = edit.changes
            {
                let edits = changes.values().next().unwrap();
                let new_text = &edits[0].new_text;
                assert!(
                    new_text.contains("set;"),
                    "interface hook should be abstract, got: {new_text}"
                );
            }
        }
    }

    #[test]
    fn get_hook_edit_contains_correct_php() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let get_action = actions.iter().find(
            |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title == "Generate get hook"),
        );

        assert!(
            get_action.is_some(),
            "should have a 'Generate get hook' action"
        );

        if let Some(CodeActionOrCommand::CodeAction(ca)) = get_action {
            let edit = ca.edit.as_ref().unwrap();
            let changes = edit.changes.as_ref().unwrap();
            let edits = changes.values().next().unwrap();
            let new_text = &edits[0].new_text;

            assert!(
                new_text.contains("get => $this->name;"),
                "get hook should reference $this->name, got: {new_text}"
            );
            assert!(
                new_text.starts_with("public string $name {"),
                "should start with property declaration, got: {new_text}"
            );
        }
    }

    #[test]
    fn set_hook_edit_contains_correct_php() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let set_action = actions.iter().find(
            |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title == "Generate set hook"),
        );

        assert!(
            set_action.is_some(),
            "should have a 'Generate set hook' action"
        );

        if let Some(CodeActionOrCommand::CodeAction(ca)) = set_action {
            let edit = ca.edit.as_ref().unwrap();
            let changes = edit.changes.as_ref().unwrap();
            let edits = changes.values().next().unwrap();
            let new_text = &edits[0].new_text;

            assert!(
                new_text.contains("set => $this->name = $value;"),
                "set hook should assign $value, got: {new_text}"
            );
        }
    }

    #[test]
    fn both_hooks_edit_contains_correct_php() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let both_action = actions.iter().find(|a| {
            matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title == "Generate get and set hooks")
        });

        assert!(
            both_action.is_some(),
            "should have a 'Generate get and set hooks' action"
        );

        if let Some(CodeActionOrCommand::CodeAction(ca)) = both_action {
            let edit = ca.edit.as_ref().unwrap();
            let changes = edit.changes.as_ref().unwrap();
            let edits = changes.values().next().unwrap();
            let new_text = &edits[0].new_text;

            assert!(
                new_text.contains("get => $this->name;"),
                "both hooks should include get, got: {new_text}"
            );
            assert!(
                new_text.contains("set => $this->name = $value;"),
                "both hooks should include set, got: {new_text}"
            );
        }
    }

    #[test]
    fn property_with_default_preserves_default() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name = 'default';\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let get_action = actions.iter().find(
            |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title == "Generate get hook"),
        );

        if let Some(CodeActionOrCommand::CodeAction(ca)) = get_action {
            let edit = ca.edit.as_ref().unwrap();
            let changes = edit.changes.as_ref().unwrap();
            let edits = changes.values().next().unwrap();
            let new_text = &edits[0].new_text;

            assert!(
                new_text.contains("= 'default'"),
                "default value should be preserved, got: {new_text}"
            );
        }
    }

    #[test]
    fn existing_hooked_property_with_get_only_offers_set() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content =
            "<?php\nclass Foo {\n    public string $name {\n        get => $this->name;\n    }\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            1,
            "property with existing get hook should only offer set, got: {:?}",
            hook_actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );

        if let CodeActionOrCommand::CodeAction(ca) = &hook_actions[0] {
            assert_eq!(ca.title, "Generate set hook");
        }
    }

    #[test]
    fn existing_hooked_property_with_both_hooks_offers_nothing() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $name {\n        get => $this->name;\n        set => $this->name = $value;\n    }\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            0,
            "property with both hooks should not offer any hook actions"
        );
    }

    #[test]
    fn no_hooks_for_enum_property() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        // Enums can't have regular properties, but let's make sure
        // the code action doesn't crash or offer hooks for enum members.
        let content = "<?php\nenum Foo: string {\n    case Bar = 'bar';\n}";

        let pos = content.find("case").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(hook_actions.len(), 0, "enums should not offer hook actions");
    }

    #[test]
    fn untyped_property_generates_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public $name;\n}";

        let pos = content.find("public $name").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            3,
            "untyped property should offer all three hook actions, got: {:?}",
            hook_actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn multi_variable_property_offers_no_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nclass Foo {\n    public string $a, $b;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            0,
            "multi-variable properties cannot have hooks"
        );
    }

    #[test]
    fn trait_property_generates_concrete_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\ntrait Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let get_action = actions.iter().find(
            |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title == "Generate get hook"),
        );

        assert!(get_action.is_some(), "trait should offer hook actions");

        if let Some(CodeActionOrCommand::CodeAction(ca)) = get_action {
            let edit = ca.edit.as_ref().unwrap();
            let changes = edit.changes.as_ref().unwrap();
            let edits = changes.values().next().unwrap();
            let new_text = &edits[0].new_text;
            assert!(
                new_text.contains("get => $this->name;"),
                "trait hooks should be concrete, got: {new_text}"
            );
        }
    }

    #[test]
    fn readonly_class_property_offers_no_hooks() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nfinal readonly class Foo {\n    public string $name;\n}";

        let pos = content.find("public string").unwrap() as u32;
        let position = offset_to_position(content, pos as usize);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: position,
                end: position,
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let hook_actions: Vec<_> = actions
            .iter()
            .filter(
                |a| matches!(a, CodeActionOrCommand::CodeAction(ca) if ca.title.contains("hook")),
            )
            .collect();

        assert_eq!(
            hook_actions.len(),
            0,
            "readonly class properties cannot have hooks in PHP 8.4"
        );
    }
}