php-lsp 0.22.2

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
//! Laravel framework support.
//!
//! Beyond generic PHP analysis, Laravel projects lean heavily on stringly-typed
//! lookups — `env('KEY')`, `config('a.b.c')`, `view('a.b')`, `route('name')`,
//! `trans('a.b')` — that resolve against files elsewhere in the project rather
//! than through normal symbol resolution. `LaravelIndex` builds a workspace-
//! scan-time index for each of these domains (`env` and `config` so far;
//! further domains are added incrementally) and wires them into
//! go-to-definition ([`resolve_string_key`]) and completion
//! ([`completions_for_string_key`]).
//!
//! Gated behind [`LaravelIndex::load`]'s project-detection check, so
//! non-Laravel workspaces pay no cost beyond the one-time
//! `artisan`/`composer.json` probe: both dispatch functions bail out on the
//! `is_laravel` flag before doing any string scanning.

mod config_index;
mod detect;
mod eloquent_guard;
mod env_index;
pub(crate) mod facades;
mod location_lookup;
pub(crate) mod request_fields;
mod route_index;
pub(crate) mod route_scaffold;
mod string_call;
mod translation_index;
mod view_index;

pub use config_index::ConfigIndex;
pub use eloquent_guard::unguarded_model_diagnostics;
pub use env_index::EnvIndex;
pub use route_index::RouteIndex;
pub use translation_index::TranslationIndex;
pub use view_index::ViewIndex;

use config_index::config_completions;
use env_index::{env_completions, missing_env_key_action};
use route_index::route_completions;
use string_call::{call_string_arg, call_string_prefix};
use translation_index::{missing_translation_json_key_action, translation_completions};
use view_index::view_completions;

use std::path::Path;

use tower_lsp_server::ls_types::{
    CodeActionOrCommand, CompletionItem, Location, Position, Range, Uri,
};

pub(crate) use string_call::find_call_sites;

/// Bare function names recognized as the `env()` string-key helper call.
const ENV_CALL_NAMES: &[&str] = &["env"];
/// Bare function names recognized as the `config()` string-key helper call.
const CONFIG_CALL_NAMES: &[&str] = &["config"];
/// Bare function names recognized as the `view()` string-key helper call.
const VIEW_CALL_NAMES: &[&str] = &["view"];
/// Bare function names recognized as translation string-key helper calls —
/// `__()` and its `trans()` alias.
const TRANS_CALL_NAMES: &[&str] = &["__", "trans"];
/// Bare function names recognized as the `route()` string-key helper call.
const ROUTE_CALL_NAMES: &[&str] = &["route"];

#[derive(Debug, Default)]
pub struct LaravelIndex {
    pub is_laravel: bool,
    pub env: EnvIndex,
    pub config: ConfigIndex,
    pub views: ViewIndex,
    pub translations: TranslationIndex,
    pub routes: RouteIndex,
}

impl LaravelIndex {
    /// Build the index for a workspace root. Returns an empty, inert index
    /// (no filesystem access beyond the detection probe) for non-Laravel
    /// roots.
    pub fn load(root: &Path) -> Self {
        if !detect::is_laravel_project(root) {
            return Self::default();
        }
        Self {
            is_laravel: true,
            env: EnvIndex::load(root),
            config: ConfigIndex::load(root),
            views: ViewIndex::load(root),
            translations: TranslationIndex::load(root),
            routes: RouteIndex::load(root),
        }
    }
}

/// The route name and its `Range`, when the cursor sits inside a
/// `route('...')` call's string argument. Thin wrapper exposing
/// `string_call::call_string_arg` scoped to [`ROUTE_CALL_NAMES`] for the
/// "Create route" quickfix (`src/actions/route_scaffold_action.rs`), which
/// lives outside this module.
pub(crate) fn route_call_at(
    doc: &crate::document::ast::ParsedDoc,
    position: Position,
) -> Option<(String, Range)> {
    call_string_arg(doc, position, ROUTE_CALL_NAMES)
}

/// Resolve the cursor position to a Laravel string-key definition — checked
/// in order: `env('KEY')`, `config('a.b.c')`, `view('a.b.c')`,
/// `__('a.b')`/`trans('a.b')`, then `route('name')`. Returns `None`
/// immediately for non-Laravel workspaces, or when the cursor isn't inside a
/// recognized call's string argument.
pub(crate) fn resolve_string_key(
    doc: &crate::document::ast::ParsedDoc,
    position: Position,
    laravel: &LaravelIndex,
) -> Option<Location> {
    if !laravel.is_laravel {
        return None;
    }
    if let Some((key, _)) = call_string_arg(doc, position, ENV_CALL_NAMES) {
        return laravel.env.get(&key).cloned();
    }
    if let Some((key, _)) = call_string_arg(doc, position, CONFIG_CALL_NAMES) {
        return laravel.config.get(&key).cloned();
    }
    if let Some((key, _)) = call_string_arg(doc, position, VIEW_CALL_NAMES) {
        return laravel.views.get(&key).cloned();
    }
    if let Some((key, _)) = call_string_arg(doc, position, TRANS_CALL_NAMES) {
        return laravel.translations.get(&key).cloned();
    }
    if let Some((key, _)) = call_string_arg(doc, position, ROUTE_CALL_NAMES) {
        return laravel.routes.get(&key).cloned();
    }
    None
}

/// Completions for the cursor position inside a recognized Laravel string-key
/// call. `Some(items)` (possibly empty) means the cursor is inside such a
/// call and normal completion should be skipped in favor of these items;
/// `None` means the cursor isn't in a recognized context at all — the caller
/// should fall through to its normal completion logic.
pub(crate) fn completions_for_string_key(
    source: &str,
    position: Position,
    laravel: Option<&LaravelIndex>,
) -> Option<Vec<CompletionItem>> {
    let laravel = laravel.filter(|l| l.is_laravel)?;
    if let Some(prefix) = call_string_prefix(source, position, ENV_CALL_NAMES) {
        return Some(env_completions(&laravel.env, &prefix));
    }
    if let Some(prefix) = call_string_prefix(source, position, CONFIG_CALL_NAMES) {
        return Some(config_completions(&laravel.config, &prefix));
    }
    if let Some(prefix) = call_string_prefix(source, position, VIEW_CALL_NAMES) {
        return Some(view_completions(&laravel.views, &prefix));
    }
    if let Some(prefix) = call_string_prefix(source, position, TRANS_CALL_NAMES) {
        return Some(translation_completions(&laravel.translations, &prefix));
    }
    if let Some(prefix) = call_string_prefix(source, position, ROUTE_CALL_NAMES) {
        return Some(route_completions(&laravel.routes, &prefix));
    }
    None
}

/// If the cursor sits on a Laravel string-key *definition* site — a `.env`
/// entry, a `config/*.php` array key, a view template's start, a
/// translation key, or a route's `->name(...)` string — returns the call
/// names to sweep the rest of the workspace for, the resolved key, and this
/// definition's own `Location` (for `include_declaration`). `None` for
/// non-Laravel workspaces or when the cursor isn't on any definition site.
///
/// Used by find-references: go-to-definition/completion start from a call
/// site and look up a key; this is the reverse direction, starting from the
/// definition and needing to know *which* key it is before a workspace
/// sweep is possible.
pub(crate) fn resolve_definition_key(
    uri: &Uri,
    position: Position,
    laravel: &LaravelIndex,
) -> Option<(&'static [&'static str], String, Location)> {
    if !laravel.is_laravel {
        return None;
    }
    if let Some(key) = laravel.env.key_at(uri, position) {
        let loc = laravel.env.get(key)?.clone();
        return Some((ENV_CALL_NAMES, key.to_string(), loc));
    }
    if let Some(key) = laravel.config.key_at(uri, position) {
        let loc = laravel.config.get(key)?.clone();
        return Some((CONFIG_CALL_NAMES, key.to_string(), loc));
    }
    if let Some(key) = laravel.views.key_at(uri, position) {
        let loc = laravel.views.get(key)?.clone();
        return Some((VIEW_CALL_NAMES, key.to_string(), loc));
    }
    if let Some(key) = laravel.translations.key_at(uri, position) {
        let loc = laravel.translations.get(key)?.clone();
        return Some((TRANS_CALL_NAMES, key.to_string(), loc));
    }
    if let Some(key) = laravel.routes.key_at(uri, position) {
        let loc = laravel.routes.get(key)?.clone();
        return Some((ROUTE_CALL_NAMES, key.to_string(), loc));
    }
    None
}

/// Quickfixes for a Laravel string-key call whose argument doesn't resolve
/// to anything in the workspace — checked at the same call sites as
/// [`resolve_string_key`], but only for domains where a safe, mechanical fix
/// exists (`env`, JSON-literal `trans`/`__`). `root` is the workspace root
/// used to locate the file to edit; `None` (no workspace root) or a
/// non-Laravel workspace yields no actions.
pub(crate) fn missing_key_actions(
    doc: &crate::document::ast::ParsedDoc,
    position: Position,
    laravel: &LaravelIndex,
    root: Option<&Path>,
) -> Vec<CodeActionOrCommand> {
    if !laravel.is_laravel {
        return Vec::new();
    }
    let Some(root) = root else {
        return Vec::new();
    };
    let mut actions = Vec::new();
    if let Some((key, _)) = call_string_arg(doc, position, ENV_CALL_NAMES)
        && laravel.env.get(&key).is_none()
        && let Some(action) = missing_env_key_action(root, &key)
    {
        actions.push(action);
    }
    if let Some((key, _)) = call_string_arg(doc, position, TRANS_CALL_NAMES)
        && laravel.translations.get(&key).is_none()
        && let Some(action) = missing_translation_json_key_action(root, &key)
    {
        actions.push(action);
    }
    actions
}

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

    #[test]
    fn load_non_laravel_root_is_empty_and_inert() {
        let tmp = tempfile::tempdir().unwrap();
        let idx = LaravelIndex::load(tmp.path());
        assert!(!idx.is_laravel);
        assert_eq!(idx.env.names().count(), 0);
        assert_eq!(idx.config.keys().count(), 0);
        assert_eq!(idx.views.names().count(), 0);
        assert_eq!(idx.translations.keys().count(), 0);
        assert_eq!(idx.routes.names().count(), 0);
    }

    #[test]
    fn load_laravel_root_builds_every_domain_index() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        std::fs::create_dir_all(tmp.path().join("config")).unwrap();
        std::fs::write(
            tmp.path().join("config").join("app.php"),
            "<?php\nreturn ['name' => 'Test'];\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("resources").join("views")).unwrap();
        std::fs::write(
            tmp.path()
                .join("resources")
                .join("views")
                .join("welcome.blade.php"),
            "<h1>Hi</h1>",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("lang").join("en")).unwrap();
        std::fs::write(
            tmp.path().join("lang").join("en").join("auth.php"),
            "<?php\nreturn ['failed' => 'Nope'];\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("routes")).unwrap();
        std::fs::write(
            tmp.path().join("routes").join("web.php"),
            "<?php\nRoute::get('/', Foo::class)->name('home');\n",
        )
        .unwrap();
        let idx = LaravelIndex::load(tmp.path());
        assert!(idx.is_laravel);
        assert!(idx.env.get("APP_NAME").is_some());
        assert!(idx.config.get("app.name").is_some());
        assert!(idx.views.get("welcome").is_some());
        assert!(idx.translations.get("auth.failed").is_some());
        assert!(idx.routes.get("home").is_some());
    }

    #[test]
    fn resolve_string_key_none_for_non_laravel() {
        let laravel = LaravelIndex::default();
        let pos = Position {
            line: 0,
            character: 12,
        };
        let doc = crate::document::ast::ParsedDoc::parse("<?php\nenv('APP_NAME');\n".to_string());
        assert!(resolve_string_key(&doc, pos, &laravel).is_none());
    }

    #[test]
    fn completions_for_string_key_none_when_laravel_is_none() {
        let pos = Position {
            line: 1,
            character: 5,
        };
        assert!(completions_for_string_key("<?php\nenv('", pos, None).is_none());
    }

    #[test]
    fn resolve_definition_key_finds_env_var_declaration() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let uri = Uri::from_file_path(tmp.path().join(".env")).unwrap();
        let (names, key, _loc) = resolve_definition_key(
            &uri,
            Position {
                line: 0,
                character: 2,
            },
            &laravel,
        )
        .unwrap();
        assert_eq!(names, ENV_CALL_NAMES);
        assert_eq!(key, "APP_NAME");
    }

    #[test]
    fn resolve_definition_key_none_when_not_on_a_definition() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let uri = Uri::from_file_path(tmp.path().join("app.php")).unwrap();
        assert!(
            resolve_definition_key(
                &uri,
                Position {
                    line: 0,
                    character: 0
                },
                &laravel
            )
            .is_none()
        );
    }

    #[test]
    fn missing_key_actions_offers_env_quickfix_for_unresolved_key() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let doc = crate::document::ast::ParsedDoc::parse("<?php\nenv('DB_HOST');\n".to_string());
        let pos = Position {
            line: 1,
            character: 6,
        };
        let actions = missing_key_actions(&doc, pos, &laravel, Some(tmp.path()));
        assert_eq!(actions.len(), 1);
        let CodeActionOrCommand::CodeAction(action) = &actions[0] else {
            panic!("expected a CodeAction");
        };
        assert_eq!(action.title, "Add 'DB_HOST' to .env");
    }

    #[test]
    fn missing_key_actions_empty_when_key_already_resolves() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let doc = crate::document::ast::ParsedDoc::parse("<?php\nenv('APP_NAME');\n".to_string());
        let pos = Position {
            line: 1,
            character: 6,
        };
        assert!(missing_key_actions(&doc, pos, &laravel, Some(tmp.path())).is_empty());
    }

    #[test]
    fn missing_key_actions_empty_for_non_laravel_workspace() {
        let tmp = tempfile::tempdir().unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let doc = crate::document::ast::ParsedDoc::parse("<?php\nenv('DB_HOST');\n".to_string());
        let pos = Position {
            line: 1,
            character: 6,
        };
        assert!(missing_key_actions(&doc, pos, &laravel, Some(tmp.path())).is_empty());
    }

    #[test]
    fn missing_key_actions_empty_without_root() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("artisan"), "#!/usr/bin/env php").unwrap();
        std::fs::write(tmp.path().join(".env"), "APP_NAME=Test\n").unwrap();
        let laravel = LaravelIndex::load(tmp.path());
        let doc = crate::document::ast::ParsedDoc::parse("<?php\nenv('DB_HOST');\n".to_string());
        let pos = Position {
            line: 1,
            character: 6,
        };
        assert!(missing_key_actions(&doc, pos, &laravel, None).is_empty());
    }
}