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
use crate::common::{create_psr4_workspace, create_test_backend};
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;

/// Helper: open a document and trigger completion at the given line/column.
async fn complete_at(
    backend: &phpantom_lsp::Backend,
    uri: &Url,
    src: &str,
    line: u32,
    character: u32,
) -> Vec<CompletionItem> {
    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: src.to_string(),
        },
    };
    backend.did_open(open_params).await;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position { line, character },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    match backend.completion(completion_params).await.unwrap() {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => vec![],
    }
}

fn method_names(items: &[CompletionItem]) -> Vec<&str> {
    items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::METHOD))
        .map(|i| i.filter_text.as_deref().unwrap_or(&i.label))
        .collect()
}

fn property_names(items: &[CompletionItem]) -> Vec<&str> {
    items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::PROPERTY))
        .map(|i| i.filter_text.as_deref().unwrap_or(&i.label))
        .collect()
}

// ─── @param-closure-this: instance method call ──────────────────────────────

/// When a method parameter has `@param-closure-this Route $callback`,
/// `$this->` inside a closure passed for that parameter should resolve
/// to `Route`, not the lexically enclosing class.
#[tokio::test]
async fn test_param_closure_this_instance_method() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_tag.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    public function middleware(string $m): self { return $this; }\n",
        "    public function prefix(string $p): self { return $this; }\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param-closure-this Route $callback\n",
        "     */\n",
        "    public function group(\\Closure $callback): void {}\n",
        "}\n",
        "class AppRoutes {\n",
        "    public function register(): void {\n",
        "        $router = new Router();\n",
        "        $router->group(function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 15: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 15, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"middleware"),
        "Expected 'middleware' from @param-closure-this Route, got: {:?}",
        names,
    );
    assert!(
        names.contains(&"prefix"),
        "Expected 'prefix' from @param-closure-this Route, got: {:?}",
        names,
    );
}

// ─── @param-closure-this with `$this` as the type ───────────────────────────

/// `@param-closure-this $this $callback` means `$this` inside the closure
/// refers to the declaring class (the class that owns the method).
#[tokio::test]
async fn test_param_closure_this_dollar_this_type() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_self.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class CacheManager {\n",
        "    public function getDefaultDriver(): string { return ''; }\n",
        "    /**\n",
        "     * @param string $driver\n",
        "     * @param \\Closure $callback\n",
        "     * @param-closure-this $this $callback\n",
        "     * @return $this\n",
        "     */\n",
        "    public function extend(string $driver, \\Closure $callback): self { return $this; }\n",
        "}\n",
        "class App {\n",
        "    public function boot(): void {\n",
        "        $mgr = new CacheManager();\n",
        "        $mgr->extend('redis', function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 15: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 15, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"getDefaultDriver"),
        "Expected 'getDefaultDriver' from @param-closure-this $this (CacheManager), got: {:?}",
        names,
    );
    assert!(
        names.contains(&"extend"),
        "Expected 'extend' from @param-closure-this $this (CacheManager), got: {:?}",
        names,
    );
}

// ─── @param-closure-this with `static` as the type ──────────────────────────

/// `@param-closure-this static $macro` means `$this` inside the closure
/// refers to the declaring class.
#[tokio::test]
async fn test_param_closure_this_static_type() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_static.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Macroable {\n",
        "    public function getMacros(): array { return []; }\n",
        "    /**\n",
        "     * @param string $name\n",
        "     * @param callable $macro\n",
        "     * @param-closure-this static $macro\n",
        "     */\n",
        "    public static function macro(string $name, callable $macro): void {}\n",
        "}\n",
        "class App {\n",
        "    public function run(): void {\n",
        "        Macroable::macro('test', function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 13: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 13, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"getMacros"),
        "Expected 'getMacros' from @param-closure-this static (Macroable), got: {:?}",
        names,
    );
}

// ─── @param-closure-this on a standalone function ───────────────────────────

/// `@param-closure-this` works on standalone functions too, not just methods.
#[tokio::test]
async fn test_param_closure_this_standalone_function() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_func.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class TestCase {\n",
        "    public function assertTrue(bool $v): void {}\n",
        "    public function assertFalse(bool $v): void {}\n",
        "}\n",
        "/**\n",
        " * @param-closure-this TestCase $callback\n",
        " */\n",
        "function test(string $name, \\Closure $callback): void {}\n",
        "class Runner {\n",
        "    public function go(): void {\n",
        "        test('example', function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 12: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 12, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"assertTrue"),
        "Expected 'assertTrue' from @param-closure-this TestCase, got: {:?}",
        names,
    );
    assert!(
        names.contains(&"assertFalse"),
        "Expected 'assertFalse' from @param-closure-this TestCase, got: {:?}",
        names,
    );
}

// ─── @param-closure-this does not leak outside the closure ──────────────────

/// `$this` outside the closure should still resolve to the lexically
/// enclosing class, not the @param-closure-this type.
#[tokio::test]
async fn test_param_closure_this_does_not_leak() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_no_leak.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    public function middleware(string $m): self { return $this; }\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param-closure-this Route $callback\n",
        "     */\n",
        "    public function group(\\Closure $callback): void {}\n",
        "}\n",
        "class AppRoutes {\n",
        "    public function ownMethod(): string { return ''; }\n",
        "    public function register(): void {\n",
        "        $router = new Router();\n",
        "        $this->\n",
        "        $router->group(function () {\n",
        "            // inside closure: $this is Route\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 14: `        $this->` — cursor OUTSIDE the closure
    let items = complete_at(&backend, &uri, src, 14, 15).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"ownMethod"),
        "Expected 'ownMethod' from lexical class AppRoutes, got: {:?}",
        names,
    );
    assert!(
        !names.contains(&"middleware"),
        "Should NOT see Route::middleware outside the closure, got: {:?}",
        names,
    );
}

// ─── @param-closure-this with property access ───────────────────────────────

/// `$this->prop` inside a closure with @param-closure-this should
/// resolve against the override type's properties.
#[tokio::test]
async fn test_param_closure_this_property_access() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_prop.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    /** @var string */\n",
        "    public string $uri = '';\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param-closure-this Route $callback\n",
        "     */\n",
        "    public function group(\\Closure $callback): void {}\n",
        "}\n",
        "class App {\n",
        "    public function run(): void {\n",
        "        $r = new Router();\n",
        "        $r->group(function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 15: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 15, 19).await;
    let props = property_names(&items);
    assert!(
        props.contains(&"uri"),
        "Expected 'uri' property from @param-closure-this Route, got: {:?}",
        props,
    );
}

// ─── @param-closure-this with FQN type ──────────────────────────────────────

/// `@param-closure-this \App\Route $callback` with a leading backslash
/// should resolve correctly.
#[tokio::test]
async fn test_param_closure_this_fqn_type() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_fqn.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    public function middleware(string $m): self { return $this; }\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param-closure-this \\Route $callback\n",
        "     */\n",
        "    public function group(\\Closure $callback): void {}\n",
        "}\n",
        "class App {\n",
        "    public function run(): void {\n",
        "        $r = new Router();\n",
        "        $r->group(function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 14: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 14, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"middleware"),
        "Expected 'middleware' from @param-closure-this \\Route, got: {:?}",
        names,
    );
}

// ─── @param-closure-this cross-file via PSR-4 ───────────────────────────────

/// The @param-closure-this type should resolve across files using the
/// class loader (PSR-4 autoloading).
#[tokio::test]
async fn test_param_closure_this_cross_file() {
    let (backend, dir) = create_psr4_workspace(
        r#"{"autoload": {"psr-4": {"App\\": "src/"}}}"#,
        &[
            (
                "src/Route.php",
                "<?php\nnamespace App;\nclass Route {\n    public function middleware(string $m): self { return $this; }\n    public function prefix(string $p): self { return $this; }\n}\n",
            ),
            (
                "src/Router.php",
                concat!(
                    "<?php\nnamespace App;\n",
                    "class Router {\n",
                    "    /**\n",
                    "     * @param-closure-this \\App\\Route $callback\n",
                    "     */\n",
                    "    public function group(\\Closure $callback): void {}\n",
                    "}\n",
                ),
            ),
        ],
    );

    let uri = Url::from_file_path(dir.path().join("src/AppRoutes.php")).unwrap();

    let src = concat!(
        "<?php\n",
        "namespace App;\n",
        "class AppRoutes {\n",
        "    public function register(): void {\n",
        "        $router = new Router();\n",
        "        $router->group(function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, src, 6, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"middleware"),
        "Expected 'middleware' from cross-file @param-closure-this Route, got: {:?}",
        names,
    );
    assert!(
        names.contains(&"prefix"),
        "Expected 'prefix' from cross-file @param-closure-this Route, got: {:?}",
        names,
    );
}

// ─── @param-closure-this second parameter ───────────────────────────────────

/// When @param-closure-this targets the second parameter, only closures
/// passed as the second argument should be affected.
#[tokio::test]
async fn test_param_closure_this_second_param() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_second.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    public function middleware(string $m): self { return $this; }\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param string $prefix\n",
        "     * @param \\Closure $callback\n",
        "     * @param-closure-this Route $callback\n",
        "     */\n",
        "    public function group(string $prefix, \\Closure $callback): void {}\n",
        "}\n",
        "class App {\n",
        "    public function run(): void {\n",
        "        $r = new Router();\n",
        "        $r->group('/api', function () {\n",
        "            $this->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 16: `            $this->` — cursor after `->`
    let items = complete_at(&backend, &uri, src, 16, 19).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"middleware"),
        "Expected 'middleware' from @param-closure-this Route on second param, got: {:?}",
        names,
    );
}

// ─── @param-closure-this with chained method call ───────────────────────────

/// `$this->method()` inside a closure with @param-closure-this should
/// resolve through the override type.
#[tokio::test]
async fn test_param_closure_this_method_chain() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///test/closure_this_chain.php").unwrap();

    let src = concat!(
        "<?php\n",
        "class Route {\n",
        "    public function middleware(string $m): self { return $this; }\n",
        "    public function prefix(string $p): self { return $this; }\n",
        "}\n",
        "class Router {\n",
        "    /**\n",
        "     * @param-closure-this Route $callback\n",
        "     */\n",
        "    public function group(\\Closure $callback): void {}\n",
        "}\n",
        "class App {\n",
        "    public function run(): void {\n",
        "        $r = new Router();\n",
        "        $r->group(function () {\n",
        "            $this->middleware('auth')->\n",
        "        });\n",
        "    }\n",
        "}\n",
    );

    // Line 15: `            $this->middleware('auth')->` — cursor after second `->`
    let items = complete_at(&backend, &uri, src, 15, 42).await;
    let names = method_names(&items);
    assert!(
        names.contains(&"prefix"),
        "Expected 'prefix' from chained call on @param-closure-this Route, got: {:?}",
        names,
    );
}

// ─── Docblock parsing unit tests ────────────────────────────────────────────

#[test]
fn test_extract_param_closure_this_basic() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = "/**\n * @param-closure-this Route $callback\n */";
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        (PhpType::parse("Route"), "$callback".to_string())
    );
}

#[test]
fn test_extract_param_closure_this_fqn() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = "/**\n * @param-closure-this \\Illuminate\\Routing\\Route $callback\n */";
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        (
            PhpType::parse("\\Illuminate\\Routing\\Route"),
            "$callback".to_string()
        )
    );
}

#[test]
fn test_extract_param_closure_this_dollar_this() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = "/**\n * @param-closure-this  $this  $callback\n */";
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        (PhpType::parse("$this"), "$callback".to_string())
    );
}

#[test]
fn test_extract_param_closure_this_static() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = "/**\n * @param-closure-this static  $macro\n */";
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], (PhpType::parse("static"), "$macro".to_string()));
}

#[test]
fn test_extract_param_closure_this_multiple() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = concat!(
        "/**\n",
        " * @param-closure-this Route $callback\n",
        " * @param-closure-this TestCase $setup\n",
        " */",
    );
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 2);
    assert_eq!(
        results[0],
        (PhpType::parse("Route"), "$callback".to_string())
    );
    assert_eq!(
        results[1],
        (PhpType::parse("TestCase"), "$setup".to_string())
    );
}

#[test]
fn test_extract_param_closure_this_no_tag() {
    use phpantom_lsp::docblock::extract_param_closure_this;

    let doc = "/**\n * @param string $name\n * @return void\n */";
    let results = extract_param_closure_this(doc);
    assert!(results.is_empty());
}

#[test]
fn test_extract_param_closure_this_missing_param_name() {
    use phpantom_lsp::docblock::extract_param_closure_this;

    // No `$paramName` after the type — should be skipped.
    let doc = "/**\n * @param-closure-this Route\n */";
    let results = extract_param_closure_this(doc);
    assert!(results.is_empty());
}

#[test]
fn test_extract_param_closure_this_coexists_with_param() {
    use phpantom_lsp::docblock::extract_param_closure_this;
    use phpantom_lsp::php_type::PhpType;

    let doc = concat!(
        "/**\n",
        " * @param string $driver\n",
        " * @param \\Closure $callback\n",
        " *\n",
        " * @param-closure-this  $this  $callback\n",
        " *\n",
        " * @return $this\n",
        " */",
    );
    let results = extract_param_closure_this(doc);
    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        (PhpType::parse("$this"), "$callback".to_string())
    );
}