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
//! Integration tests for the `fix` CLI module.
//!
//! Tests exercise the unused-import fixer with a real `Backend` to
//! verify end-to-end correctness: parse → detect unused → build edits
//! → apply edits → verify output.

use crate::common::create_test_backend;
use phpantom_lsp::Backend;

/// Helper: parse a PHP file into the backend and run the unused-import
/// fixer, returning the fixed content.
fn fix_unused_imports(backend: &Backend, uri: &str, content: &str) -> String {
    backend.update_ast(uri, content);

    let mut diagnostics = Vec::new();
    backend.collect_unused_import_diagnostics(uri, content, &mut diagnostics);

    if diagnostics.is_empty() {
        return content.to_string();
    }

    use std::collections::HashSet;
    use tower_lsp::lsp_types::*;

    let removed_import_lines: HashSet<usize> = diagnostics
        .iter()
        .map(|d| d.range.start.line as usize)
        .collect();

    let mut edits: Vec<TextEdit> = diagnostics
        .iter()
        .map(|d| {
            phpantom_lsp::code_actions::build_line_deletion_edit(
                content,
                &d.range,
                &removed_import_lines,
            )
        })
        .collect();

    edits.sort_by(|a, b| b.range.start.cmp(&a.range.start));

    apply_text_edits(content, &edits)
}

/// Apply reverse-sorted text edits to content.
fn apply_text_edits(content: &str, edits: &[tower_lsp::lsp_types::TextEdit]) -> String {
    let mut result = content.to_string();

    for edit in edits {
        let start = lsp_position_to_byte_offset(&result, edit.range.start);
        let end = lsp_position_to_byte_offset(&result, edit.range.end);

        if start <= end && end <= result.len() {
            result.replace_range(start..end, &edit.new_text);
        }
    }

    result
}

/// Convert LSP Position to byte offset.
fn lsp_position_to_byte_offset(content: &str, pos: tower_lsp::lsp_types::Position) -> usize {
    let mut offset = 0;
    for (i, line) in content.lines().enumerate() {
        if i == pos.line as usize {
            let mut utf16_units = 0u32;
            for (byte_idx, ch) in line.char_indices() {
                if utf16_units >= pos.character {
                    return offset + byte_idx;
                }
                utf16_units += ch.len_utf16() as u32;
            }
            return offset + line.len();
        }
        offset += line.len() + 1;
    }
    content.len()
}

// ── Single unused import ────────────────────────────────────────────────────

#[test]
fn removes_single_unused_import() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;

class Foo {}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        !result.contains("use App\\Models\\User"),
        "Unused import should be removed. Got:\n{result}"
    );
    assert!(
        result.contains("class Foo {}"),
        "Class declaration should remain"
    );
}

// ── Multiple unused imports ─────────────────────────────────────────────────

#[test]
fn removes_multiple_unused_imports() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;
use App\Models\Post;
use App\Models\Comment;

class Foo {}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        !result.contains("use App\\Models\\User"),
        "User import should be removed"
    );
    assert!(
        !result.contains("use App\\Models\\Post"),
        "Post import should be removed"
    );
    assert!(
        !result.contains("use App\\Models\\Comment"),
        "Comment import should be removed"
    );
    assert!(
        result.contains("class Foo {}"),
        "Class declaration should remain"
    );
}

// ── Used import is preserved ────────────────────────────────────────────────

#[test]
fn preserves_used_import() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;

class Foo {
    public function bar(): User {
        return new User();
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Models\\User"),
        "Used import should be preserved. Got:\n{result}"
    );
}

// ── Mix of used and unused imports ──────────────────────────────────────────

#[test]
fn removes_only_unused_from_mixed_imports() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;
use App\Models\Post;
use App\Models\Comment;

class Foo {
    public function bar(): User {
        return new User();
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Models\\User"),
        "Used import (User) should be preserved"
    );
    assert!(
        !result.contains("use App\\Models\\Post"),
        "Unused import (Post) should be removed"
    );
    assert!(
        !result.contains("use App\\Models\\Comment"),
        "Unused import (Comment) should be removed"
    );
}

// ── No imports at all ───────────────────────────────────────────────────────

#[test]
fn no_imports_returns_unchanged() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

class Foo {
    public function bar(): void {}
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);
    assert_eq!(result, content);
}

// ── All imports used ────────────────────────────────────────────────────────

#[test]
fn all_imports_used_returns_unchanged() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;
use App\Models\Post;

class Foo {
    public function bar(): User {
        return new User();
    }
    public function baz(): Post {
        return new Post();
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);
    assert_eq!(result, content);
}

// ── Group import with one unused member ─────────────────────────────────────

#[test]
fn removes_unused_member_from_group_import() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\{User, Post};

class Foo {
    public function bar(): User {
        return new User();
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("User"),
        "Used member (User) should be preserved"
    );
    assert!(
        !result.contains("Post"),
        "Unused member (Post) should be removed from group"
    );
}

// ── Group import with all members unused ────────────────────────────────────

#[test]
fn removes_entire_group_import_when_all_unused() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\{User, Post};

class Foo {}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        !result.contains("use App\\Models"),
        "Entire group import should be removed. Got:\n{result}"
    );
    assert!(
        result.contains("class Foo {}"),
        "Class declaration should remain"
    );
}

// ── Blank line collapsing ───────────────────────────────────────────────────

#[test]
fn collapses_blank_lines_after_removing_all_imports() {
    let backend = create_test_backend();
    let content = "<?php\n\nnamespace App;\n\nuse App\\Models\\User;\n\nclass Foo {}\n";

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    // Should not have double blank lines where the import was.
    assert!(
        !result.contains("\n\n\n"),
        "Should not leave triple newlines. Got:\n{result}"
    );
}

// ── Static method reference keeps import ────────────────────────────────────

#[test]
fn preserves_import_used_in_static_call() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Utils\Helper;

class Foo {
    public function bar(): void {
        Helper::doSomething();
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Utils\\Helper"),
        "Import used in static call should be preserved"
    );
}

// ── Import used in type hint ────────────────────────────────────────────────

#[test]
fn preserves_import_used_in_parameter_type_hint() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;

class Foo {
    public function bar(User $user): void {}
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Models\\User"),
        "Import used as parameter type hint should be preserved"
    );
}

// ── Import used in docblock ─────────────────────────────────────────────────

#[test]
fn preserves_import_referenced_in_phpdoc_return_tag() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;

class Foo {
    /** @return User */
    public function bar() {}
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Models\\User"),
        "Import referenced in @return should be preserved"
    );
}

// ── Braced namespace ────────────────────────────────────────────────────────

#[test]
fn removes_unused_import_in_braced_namespace() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App {
    use App\Models\User;
    use App\Models\Post;

    class Foo {
        public function bar(): User {
            return new User();
        }
    }
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Models\\User"),
        "Used import should be preserved in braced namespace"
    );
    assert!(
        !result.contains("use App\\Models\\Post"),
        "Unused import should be removed from braced namespace"
    );
}

// ── Trait use statement is not removed ───────────────────────────────────────

#[test]
fn does_not_remove_trait_use_statements() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Traits\HasName;

class Foo {
    use HasName;
}
"#;

    let result = fix_unused_imports(&backend, "file:///test.php", content);

    assert!(
        result.contains("use App\\Traits\\HasName"),
        "Namespace-level import for trait should be preserved (used by trait-use inside class)"
    );
}

// ── Idempotency ─────────────────────────────────────────────────────────────

#[test]
fn fix_is_idempotent() {
    let backend = create_test_backend();
    let content = r#"<?php

namespace App;

use App\Models\User;
use App\Models\Post;

class Foo {
    public function bar(): User {
        return new User();
    }
}
"#;

    let first_pass = fix_unused_imports(&backend, "file:///test.php", content);

    // Re-parse with the fixed content and fix again.
    let second_pass = fix_unused_imports(&backend, "file:///test.php", &first_pass);

    assert_eq!(
        first_pass, second_pass,
        "Running fix twice should produce the same result"
    );
}