php-lsp 0.4.0

A PHP Language Server Protocol implementation
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
//! Completion coverage across trigger characters and contexts.
//!
//! Each test asserts on the presence of specific labels rather than full
//! snapshots — completion lists contain many built-ins/keywords whose ordering
//! is driven by ranking heuristics.

mod common;

use common::{TestServer, render_completion};
use expect_test::expect;

async fn labels(s: &mut TestServer, src: &str) -> Vec<String> {
    let opened = s.open_fixture(src).await;
    let c = opened.cursor().clone();
    let resp = s.completion(&c.path, c.line, c.character).await;
    let items = match &resp["result"] {
        v if v.is_array() => v.as_array().cloned().unwrap_or_default(),
        v if v["items"].is_array() => v["items"].as_array().cloned().unwrap_or_default(),
        _ => vec![],
    };
    items
        .iter()
        .filter_map(|i| i["label"].as_str().map(str::to_owned))
        .collect()
}

#[tokio::test]
async fn completion_arrow_method() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
class Greeter {
    public function hello(): string { return 'hi'; }
    public function bye(): void {}
}
$g = new Greeter();
$g->h$0
"#,
        )
        .await;
    expect![[r#"
        Method      bye
        Method      hello"#]]
    .assert_eq(&out);
}

#[tokio::test]
async fn completion_arrow_property() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
class User {
    public string $name = '';
    public int $age = 0;
}
$u = new User();
$u->na$0
"#,
    )
    .await;
    assert!(labels.iter().any(|l| l == "name" || l == "$name"));
}

#[tokio::test]
async fn completion_double_colon_static_method() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
class Reg {
    public static function get(): void {}
    public static function set(): void {}
}
Reg::$0
"#,
        )
        .await;
    expect![[r#"
        Variable    $GLOBALS
        Variable    $_COOKIE
        Variable    $_ENV
        Variable    $_FILES
        Variable    $_GET
        Variable    $_POST
        Variable    $_REQUEST
        Variable    $_SERVER
        Variable    $_SESSION
        Class       Reg
        Constant    __CLASS__
        Constant    __DIR__
        Constant    __FILE__
        Constant    __FUNCTION__
        Constant    __LINE__
        Constant    __METHOD__
        Constant    __NAMESPACE__
        Constant    __TRAIT__
        Function    abs
        Keyword     abstract
        Function    acos
        Function    addslashes
        Keyword     and
        Keyword     array
        Function    array_chunk
        Function    array_combine
        Function    array_diff
        Function    array_fill
        Function    array_fill_keys
        Function    array_filter
        Function    array_flip
        Function    array_intersect
        Function    array_key_exists
        Function    array_keys
        Function    array_map
        Function    array_merge
        Function    array_pad
        Function    array_pop
        Function    array_push
        Function    array_reduce
        Function    array_replace
        Function    array_reverse
        Function    array_search
        Function    array_shift
        Function    array_slice
        Function    array_splice
        Function    array_unique
        Function    array_unshift
        Function    array_values
        Function    array_walk
        Function    array_walk_recursive
        Function    arsort
        Keyword     as
        Function    asin
        Function    asort
        Function    atan
        Function    atan2
        Function    base64_decode
        Function    base64_encode
        Function    basename
        Function    boolval
        Keyword     break
        Function    call_user_func
        Function    call_user_func_array
        Keyword     callable
        Keyword     case
        Keyword     catch
        Function    ceil
        Function    checkdate
        Keyword     class
        Function    class_exists
        Keyword     clone
        Function    closedir
        Function    compact
        Keyword     const
        Function    constant
        Keyword     continue
        Function    copy
        Function    cos
        Function    count
        Function    date
        Function    date_add
        Function    date_create
        Function    date_diff
        Function    date_format
        Function    date_sub
        Keyword     declare
        Keyword     default
        Function    define
        Function    defined
        Keyword     die
        Function    dirname
        Keyword     do
        Keyword     echo
        Keyword     else
        Keyword     elseif
        Keyword     empty
        Keyword     enddeclare
        Keyword     endfor
        Keyword     endforeach
        Keyword     endif
        Keyword     endswitch
        Keyword     endwhile
        Keyword     enum
        Keyword     eval
        Keyword     exit
        Function    exp
        Function    explode
        Keyword     extends
        Function    extract
        Keyword     false
        Function    fclose
        Function    feof
        Function    fgets
        Function    file_exists
        Function    file_get_contents
        Function    file_put_contents
        Keyword     final
        Keyword     finally
        Function    floatval
        Function    floor
        Function    fmod
        Keyword     fn
        Function    fopen
        Keyword     for
        Keyword     foreach
        Function    fputs
        Function    fread
        Function    fseek
        Function    ftell
        Keyword     function
        Function    function_exists
        Function    fwrite
        Method      get
        Function    get_class
        Function    get_parent_class
        Function    gettype
        Function    glob
        Keyword     global
        Keyword     goto
        Function    hash
        Function    header
        Function    headers_sent
        Function    htmlentities
        Function    htmlspecialchars
        Function    http_build_query
        Keyword     if
        Keyword     implements
        Function    implode
        Function    in_array
        Keyword     include
        Keyword     include_once
        Keyword     instanceof
        Keyword     insteadof
        Function    intdiv
        Keyword     interface
        Function    interface_exists
        Function    intval
        Function    is_a
        Function    is_array
        Function    is_bool
        Function    is_callable
        Function    is_dir
        Function    is_double
        Function    is_file
        Function    is_finite
        Function    is_float
        Function    is_infinite
        Function    is_int
        Function    is_integer
        Function    is_long
        Function    is_nan
        Function    is_null
        Function    is_numeric
        Function    is_object
        Function    is_readable
        Function    is_string
        Function    is_subclass_of
        Function    is_writable
        Keyword     isset
        Function    join
        Function    json_decode
        Function    json_encode
        Function    krsort
        Function    ksort
        Function    lcfirst
        Keyword     list
        Function    log
        Function    ltrim
        Keyword     match
        Function    max
        Function    md5
        Function    method_exists
        Function    microtime
        Function    min
        Function    mkdir
        Function    mktime
        Function    mt_rand
        Keyword     namespace
        Keyword     new
        Function    nl2br
        Keyword     null
        Function    number_format
        Function    ob_end_clean
        Function    ob_get_clean
        Function    ob_start
        Function    opendir
        Keyword     or
        Function    parse_str
        Function    parse_url
        Function    pathinfo
        Function    pi
        Function    pow
        Function    preg_match
        Function    preg_match_all
        Function    preg_quote
        Function    preg_replace
        Function    preg_split
        Keyword     print
        Function    print_r
        Function    printf
        Keyword     private
        Function    property_exists
        Keyword     protected
        Keyword     public
        Function    rand
        Function    random_int
        Function    range
        Function    rawurldecode
        Function    rawurlencode
        Function    readdir
        Keyword     readonly
        Function    realpath
        Function    rename
        Keyword     require
        Keyword     require_once
        Keyword     return
        Function    rewind
        Function    rmdir
        Function    round
        Function    rsort
        Function    rtrim
        Function    scandir
        Keyword     self
        Function    serialize
        Function    session_destroy
        Function    session_start
        Method      set
        Function    setcookie
        Function    settype
        Function    sha1
        Function    sin
        Function    sleep
        Function    sort
        Function    sprintf
        Function    sqrt
        Keyword     static
        Function    str_contains
        Function    str_ends_with
        Function    str_pad
        Function    str_repeat
        Function    str_replace
        Function    str_split
        Function    str_starts_with
        Function    str_word_count
        Function    strcasecmp
        Function    strcmp
        Function    strip_tags
        Function    stripslashes
        Function    stristr
        Function    strlen
        Function    strncasecmp
        Function    strncmp
        Function    strpos
        Function    strrpos
        Function    strstr
        Function    strtolower
        Function    strtotime
        Function    strtoupper
        Function    strval
        Function    substr
        Function    substr_count
        Function    substr_replace
        Keyword     switch
        Function    tan
        Keyword     throw
        Function    time
        Keyword     trait
        Function    trim
        Keyword     true
        Keyword     try
        Function    uasort
        Function    ucfirst
        Function    ucwords
        Function    uksort
        Function    unlink
        Function    unserialize
        Function    unset
        Function    urldecode
        Function    urlencode
        Keyword     use
        Function    usleep
        Function    usort
        Keyword     var
        Function    var_dump
        Function    var_export
        Function    vsprintf
        Keyword     while
        Keyword     xor
        Keyword     yield"#]]
    .assert_eq(&out);
}

#[tokio::test]
async fn completion_namespace_prefix() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"//- /src/App/Greeter.php
<?php
namespace App;
class Greeter {}

//- /src/main.php
<?php
$g = new \App\$0
"#,
    )
    .await;
    assert!(
        labels.iter().any(|l| l == "Greeter"),
        "expected Greeter in namespace-prefix completions: {labels:?}"
    );
}

#[tokio::test]
async fn completion_keyword_in_top_level() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
func$0
"#,
    )
    .await;
    assert!(labels.iter().any(|l| l == "function"));
}

#[tokio::test]
async fn completion_variable_in_scope() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
function f(string $name, int $count): void {
    $na$0
}
"#,
    )
    .await;
    assert!(
        labels.iter().any(|l| l == "$name"),
        "expected $name: {labels:?}"
    );
}

#[tokio::test]
async fn completion_method_does_not_leak_to_unrelated_classes() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
class A { public function foo(): void {} }
class B { public function bar(): void {} }
$a = new A();
$a->$0
"#,
    )
    .await;
    assert!(labels.iter().any(|l| l == "foo"));
    assert!(
        !labels.iter().any(|l| l == "bar"),
        "B::bar should not appear in A completion: {labels:?}"
    );
}

/// `Status::$0` on a PHP 8.1 enum must offer the declared cases. The server
/// returns them as fully-qualified labels (`Status::Active`, `Status::Inactive`)
/// alongside the global completion list. Both labels must be present.
#[tokio::test]
async fn completion_enum_case_access() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
enum Status { case Active; case Inactive; }
Status::$0
"#,
    )
    .await;
    assert!(
        labels.iter().any(|l| l == "Status::Active"),
        "expected Status::Active in enum case completions: {labels:?}"
    );
    assert!(
        labels.iter().any(|l| l == "Status::Inactive"),
        "expected Status::Inactive in enum case completions: {labels:?}"
    );
}

/// `new $0` must include class names so users can pick from defined classes.
#[tokio::test]
async fn completion_after_new_offers_class_names() {
    let mut s = TestServer::new().await;
    let labels = labels(
        &mut s,
        r#"<?php
class Widget {}
class Gadget {}
$x = new $0
"#,
    )
    .await;
    assert!(
        labels.iter().any(|l| l == "Widget"),
        "expected Widget in `new` completions: {labels:?}"
    );
    assert!(
        labels.iter().any(|l| l == "Gadget"),
        "expected Gadget in `new` completions: {labels:?}"
    );
}

/// Verify that `completionItem/resolve` is wired up end-to-end: request a
/// completion list, pick an item, resolve it, and check the `detail` field is
/// populated.
#[tokio::test]
async fn completion_resolve_returns_item() {
    let mut server = TestServer::new().await;
    let opened = server
        .open_fixture(
            r#"<?php
function resolveMe(): void {}
resolveM$0
"#,
        )
        .await;
    let c = opened.cursor();

    let comp = server.completion(&c.path, c.line, c.character).await;
    let items = match &comp["result"] {
        v if v.is_array() => v.as_array().unwrap().to_vec(),
        v if v["items"].is_array() => v["items"].as_array().unwrap().to_vec(),
        _ => vec![],
    };
    assert!(
        !items.is_empty(),
        "expected completions for 'resolveM' prefix: {:?}",
        comp["result"]
    );

    let resolve_me = items
        .iter()
        .find(|i| i["label"].as_str() == Some("resolveMe"))
        .cloned()
        .expect("resolveMe must appear in completions for its own prefix");

    let resp = server.completion_resolve(resolve_me).await;

    assert!(
        resp["error"].is_null(),
        "completionItem/resolve error: {resp:?}"
    );
    assert!(resp["result"].is_object(), "expected resolved item object");
    let detail = resp["result"]["detail"].as_str().unwrap_or("");
    assert!(
        detail.contains("resolveMe"),
        "resolved item must have detail populated with the function signature: {:?}",
        resp["result"]
    );
}

#[tokio::test]
async fn completion_this_arrow_includes_trait_methods() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
trait Counter {
    public function tick(): void {}
    public function reset(): void {}
}
class Timer {
    use Counter;
    public function run(): void { $this->$0t; }
}
"#,
        )
        .await;
    expect![[r#"
        Method      reset
        Method      run
        Method      tick"#]]
    .assert_eq(&out);
}

// ── Attribute completion filtering ───────────────────────────────────────────

/// `#[` must only offer classes that carry `#[\Attribute]` — a plain class
/// without it must not appear.
#[tokio::test]
async fn completion_attribute_bracket_excludes_non_attribute_classes() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
#[\Attribute]
class MyRoute {}

class PlainClass {}

#[$0
"#,
        )
        .await;
    expect![[r#"
        Class       MyRoute"#]]
    .assert_eq(&out);
}

/// Cross-file: a class in another file that carries `#[\Attribute]` must appear,
/// while one that doesn't must be excluded.
#[tokio::test]
async fn completion_attribute_bracket_cross_file_filters_non_attributes() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"//- /src/attrs.php
<?php
#[\Attribute]
class ValidAttr {}

class NotAnAttr {}

//- /src/main.php
<?php
#[$0
"#,
        )
        .await;
    expect![[r#"
        Class       ValidAttr"#]]
    .assert_eq(&out);
}

/// `#[` on a class-level position must not offer method-only attributes
/// (those with `TARGET_METHOD = 4` exclusively).
/// The cursor is placed right after `#[`, with `class MyClass {}` on the next
/// line, so the server can infer the attribute target context.
#[tokio::test]
async fn completion_attribute_bracket_target_filters_class_context() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
#[\Attribute(\Attribute::TARGET_CLASS)]
class ClassOnlyAttr {}

#[\Attribute(\Attribute::TARGET_METHOD)]
class MethodOnlyAttr {}

#[\Attribute(\Attribute::TARGET_ALL)]
class AnyAttr {}

#[$0
class MyClass {}
"#,
        )
        .await;
    // AnyAttr (63 & 1 ≠ 0) and ClassOnlyAttr (1 & 1 ≠ 0) pass;
    // MethodOnlyAttr (4 & 1 = 0) is excluded.
    expect![[r#"
        Class       AnyAttr
        Class       ClassOnlyAttr"#]]
    .assert_eq(&out);
}

/// `#[` completions must exclude non-class symbols: interfaces, enums, and
/// traits cannot carry `#[\Attribute]` so they must never appear.
#[tokio::test]
async fn completion_attribute_bracket_excludes_non_class_types() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
#[\Attribute]
class ValidAttr {}

interface MyInterface {}
enum MyEnum {}
trait MyTrait {}

#[$0
"#,
        )
        .await;
    expect![[r#"
        Class       ValidAttr"#]]
    .assert_eq(&out);
}

/// `#[` before a function must show METHOD-targeted attributes but exclude
/// CLASS-only ones. Covers the `infer_attribute_target` branch returning `2|4`.
#[tokio::test]
async fn completion_attribute_bracket_target_filters_function_context() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
#[\Attribute(\Attribute::TARGET_CLASS)]
class ClassOnlyAttr {}

#[\Attribute(\Attribute::TARGET_METHOD)]
class MethodOnlyAttr {}

#[\Attribute(\Attribute::TARGET_ALL)]
class AnyAttr {}

#[$0
function doSomething(): void {}
"#,
        )
        .await;
    // AnyAttr (63 & 6 ≠ 0) and MethodOnlyAttr (4 & 6 ≠ 0) pass;
    // ClassOnlyAttr (1 & 6 = 0) is excluded.
    expect![[r#"
        Class       AnyAttr
        Class       MethodOnlyAttr"#]]
    .assert_eq(&out);
}

/// Snapshot test: `#[` must return ONLY attribute classes — no keywords,
/// built-ins, or plain classes leaking through.
#[tokio::test]
async fn completion_attribute_bracket_returns_only_attribute_classes() {
    let mut s = TestServer::new().await;
    let out = s
        .check_completion(
            r#"<?php
#[\Attribute]
class Middleware {}

#[\Attribute]
class MyRoute {}

class PlainClass {}

#[$0
"#,
        )
        .await;
    expect![[r#"
        Class       Middleware
        Class       MyRoute"#]]
    .assert_eq(&out);
}

/// Trigger-character path (`triggerKind: 2`, `triggerCharacter: "["`) must
/// also restrict completions to `#[\Attribute]`-annotated classes.
#[tokio::test]
async fn completion_attribute_bracket_trigger_char_filters_non_attributes() {
    let mut s = TestServer::new().await;
    let opened = s
        .open_fixture(
            r#"<?php
#[\Attribute]
class ValidAttr {}

class NotAnAttr {}

#[$0
"#,
        )
        .await;
    let c = opened.cursor().clone();
    let uri = s.uri(&c.path);
    let resp = s
        .client()
        .request(
            "textDocument/completion",
            serde_json::json!({
                "textDocument": { "uri": uri },
                "position": { "line": c.line, "character": c.character },
                "context": { "triggerKind": 2, "triggerCharacter": "[" },
            }),
        )
        .await;
    let out = render_completion(&resp);
    expect![[r#"
        Class       ValidAttr"#]]
    .assert_eq(&out);
}