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
//! Integration tests for the "Promote constructor parameter" code action.
//!
//! These tests exercise the full pipeline: parsing PHP source, finding
//! a promotable constructor parameter under the cursor, and generating
//! the `WorkspaceEdit` that removes the property declaration, removes
//! the assignment, and adds a visibility modifier to the parameter.

use crate::common::create_test_backend;
use tower_lsp::lsp_types::*;

/// Helper: send a code action request at the given line/character and
/// return the list of code actions.
fn get_code_actions(
    backend: &phpantom_lsp::Backend,
    uri: &str,
    content: &str,
    line: u32,
    character: u32,
) -> Vec<CodeActionOrCommand> {
    let params = CodeActionParams {
        text_document: TextDocumentIdentifier {
            uri: uri.parse().unwrap(),
        },
        range: Range {
            start: Position::new(line, character),
            end: Position::new(line, character),
        },
        context: CodeActionContext {
            diagnostics: vec![],
            only: None,
            trigger_kind: None,
        },
        work_done_progress_params: WorkDoneProgressParams {
            work_done_token: None,
        },
        partial_result_params: PartialResultParams {
            partial_result_token: None,
        },
    };

    backend.handle_code_action(uri, content, &params)
}

/// Find the "Promote to constructor property" code action from a list.
fn find_promote_action(actions: &[CodeActionOrCommand]) -> Option<&CodeAction> {
    actions.iter().find_map(|a| match a {
        CodeActionOrCommand::CodeAction(ca) if ca.title == "Promote to constructor property" => {
            Some(ca)
        }
        _ => None,
    })
}

/// Apply a workspace edit to the content and return the result.
fn apply_edit(content: &str, edit: &WorkspaceEdit) -> String {
    let changes = edit.changes.as_ref().expect("edit should have changes");
    let edits = changes
        .values()
        .next()
        .expect("should have edits for one URI");

    // Sort edits by start position descending so we can apply back-to-front.
    let mut sorted: Vec<&TextEdit> = edits.iter().collect();
    sorted.sort_by(|a, b| {
        b.range
            .start
            .line
            .cmp(&a.range.start.line)
            .then(b.range.start.character.cmp(&a.range.start.character))
    });

    let mut result = content.to_string();
    for edit in sorted {
        let start = position_to_offset(&result, edit.range.start);
        let end = position_to_offset(&result, edit.range.end);
        result.replace_range(start..end, &edit.new_text);
    }
    result
}

/// Convert an LSP Position to a byte offset.
fn position_to_offset(content: &str, pos: Position) -> usize {
    let mut offset = 0;
    for (i, line) in content.lines().enumerate() {
        if i == pos.line as usize {
            return offset + pos.character as usize;
        }
        offset += line.len() + 1; // +1 for '\n'
    }
    offset
}

// ── Basic promotion ─────────────────────────────────────────────────────────

#[test]
fn promotes_private_property() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}
";
    // Cursor on `$name` in the constructor parameter list (line 4, on "string $name").
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should offer promote action");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private string $name)"),
        "parameter should have private visibility: {result}"
    );
    assert!(
        !result.contains("private string $name;"),
        "property declaration should be removed: {result}"
    );
    assert!(
        !result.contains("$this->name = $name;"),
        "assignment should be removed: {result}"
    );
}

#[test]
fn promotes_protected_property() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    protected int $age;

    public function __construct(int $age) {
        $this->age = $age;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should offer promote action");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("protected int $age)"),
        "should use protected: {result}"
    );
}

#[test]
fn promotes_readonly_property() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private readonly string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should offer promote action");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private readonly string $name)"),
        "should include readonly: {result}"
    );
}

// ── Default value carry-over ────────────────────────────────────────────────

#[test]
fn carries_over_default_value() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $status = 'active';

    public function __construct(string $status) {
        $this->status = $status;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should offer promote action");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private string $status = 'active')"),
        "should carry default value: {result}"
    );
}

// ── Rejection cases ─────────────────────────────────────────────────────────

#[test]
fn no_action_for_non_constructor() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $name;

    public function setName(string $name): void {
        $this->name = $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions);
    assert!(action.is_none(), "should not offer for non-constructor");
}

#[test]
fn no_action_for_already_promoted() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    public function __construct(private string $name) {}
}
";
    let actions = get_code_actions(&backend, uri, content, 2, 40);
    let action = find_promote_action(&actions);
    assert!(action.is_none(), "should not offer for already-promoted");
}

#[test]
fn no_action_when_no_matching_property() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    public function __construct(string $name) {
        echo $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 2, 35);
    let action = find_promote_action(&actions);
    assert!(
        action.is_none(),
        "should not offer when no matching property"
    );
}

#[test]
fn no_action_when_param_used_elsewhere() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
        echo $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions);
    assert!(
        action.is_none(),
        "should not offer when param used elsewhere"
    );
}

#[test]
fn no_action_for_static_property() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private static string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions);
    assert!(action.is_none(), "should not offer for static property");
}

// ── Multiple parameters ─────────────────────────────────────────────────────

#[test]
fn promotes_only_targeted_parameter() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $name;
    private int $age;

    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
";
    // Cursor on `$age` parameter.
    let actions = get_code_actions(&backend, uri, content, 5, 50);
    let action = find_promote_action(&actions).expect("should offer promote for $age");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    // $age should be promoted.
    assert!(
        result.contains("private int $age)"),
        "$age should be promoted: {result}"
    );
    // $name property and assignment should remain untouched.
    assert!(
        result.contains("private string $name;"),
        "$name property should remain: {result}"
    );
    assert!(
        result.contains("$this->name = $name;"),
        "$name assignment should remain: {result}"
    );
}

// ── Namespace ───────────────────────────────────────────────────────────────

#[test]
fn works_in_namespace() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
namespace App\\Models;

class User {
    private string $email;

    public function __construct(string $email) {
        $this->email = $email;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 6, 35);
    let action = find_promote_action(&actions).expect("should work in namespace");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private string $email)"),
        "should promote in namespace: {result}"
    );
}

// ── Union / nullable types ──────────────────────────────────────────────────

#[test]
fn promotes_with_union_type() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private int|string $id;

    public function __construct(int|string $id) {
        $this->id = $id;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should handle union types");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private int|string $id)"),
        "should preserve union type: {result}"
    );
}

#[test]
fn promotes_with_nullable_type() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private ?string $name;

    public function __construct(?string $name) {
        $this->name = $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should handle nullable types");
    let result = apply_edit(content, action.edit.as_ref().unwrap());

    assert!(
        result.contains("private ?string $name)"),
        "should preserve nullable type: {result}"
    );
}

// ── Code action kind ────────────────────────────────────────────────────────

#[test]
fn action_has_correct_kind() {
    let backend = create_test_backend();
    let uri = "file:///test.php";
    let content = "\
<?php
class Foo {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}
";
    let actions = get_code_actions(&backend, uri, content, 4, 35);
    let action = find_promote_action(&actions).expect("should offer promote action");
    assert_eq!(
        action.kind,
        Some(CodeActionKind::new("refactor.rewrite")),
        "should be a refactor.rewrite action"
    );
}