Skip to main content

rust_anything/lang/
php.rs

1//! PHP: composer.json packages and PSR-4 roots, `require`/`use` imports, risks, the
2//! Composer-to-crate table, and exports (functions and public static methods) with native and
3//! phpdoc types mapped into the TS-like type dialect.
4
5use std::collections::HashMap;
6use std::path::Path;
7
8use anyhow::Result;
9use serde_json::Value;
10use tree_sitter::Node;
11
12use super::syntax::{self, named_children, text};
13use crate::risks::{Risk, regex_needs_fancy};
14use crate::ts::deps::CrateMatch;
15use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
16use crate::ts::exports::{ExportedFn, Param};
17use crate::ts::scan::{FileFacts, Import};
18
19fn language() -> tree_sitter::Language {
20    tree_sitter_php::LANGUAGE_PHP.into()
21}
22
23const SKIP_DIRS: &[&str] = &[
24    "vendor",
25    "node_modules",
26    "var",
27    "storage",
28    "cache",
29    "target",
30    ".phpunit.cache",
31];
32
33// ---- discovery -------------------------------------------------------------------------------
34
35/// Composer packages that are PHP itself or its extensions, not dependencies to port.
36fn is_platform(name: &str) -> bool {
37    name == "php" || name.starts_with("ext-") || name.starts_with("lib-") || !name.contains('/')
38}
39
40/// `require` and `require-dev` package names, and the first PSR-4 source folder.
41fn composer(text: &str) -> (Option<String>, Vec<String>, Vec<String>, Option<String>) {
42    let Ok(doc) = serde_json::from_str::<Value>(text) else {
43        return (None, Vec::new(), Vec::new(), None);
44    };
45    let names = |key: &str| -> Vec<String> {
46        doc[key]
47            .as_object()
48            .map(|o| o.keys().filter(|k| !is_platform(k)).cloned().collect())
49            .unwrap_or_default()
50    };
51    let src = doc["autoload"]["psr-4"].as_object().and_then(|o| {
52        o.values().find_map(|v| match v {
53            Value::String(s) => Some(s.trim_end_matches('/').to_string()),
54            Value::Array(a) => a
55                .first()
56                .and_then(Value::as_str)
57                .map(|s| s.trim_end_matches('/').to_string()),
58            _ => None,
59        })
60    });
61    (
62        doc["name"].as_str().map(str::to_string),
63        names("require"),
64        names("require-dev"),
65        src,
66    )
67}
68
69pub fn discover(root: &Path) -> Result<Workspace> {
70    let mut packages: Vec<Package> = Vec::new();
71    let mut files = Vec::new();
72    let walker = crate::walk::filtered(root, |e| {
73        !(e.file_type().is_some_and(|t| t.is_dir())
74            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
75    })
76    .hidden(true)
77    .require_git(false)
78    .build();
79    for entry in walker.flatten() {
80        if !entry.file_type().is_some_and(|t| t.is_file()) {
81            continue;
82        }
83        let Ok(rel) = entry.path().strip_prefix(root) else {
84            continue;
85        };
86        let rel = rel.to_string_lossy().replace('\\', "/");
87        let name = rel.rsplit('/').next().unwrap_or(&rel);
88        let dir = rel
89            .rsplit_once('/')
90            .map_or(String::new(), |(d, _)| d.to_string());
91        if name == "composer.json" {
92            let (pkg_name, deps, dev, src) =
93                composer(&std::fs::read_to_string(entry.path()).unwrap_or_default());
94            packages.push(Package {
95                name: pkg_name.unwrap_or_else(|| {
96                    if dir.is_empty() {
97                        root.file_name()
98                            .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
99                    } else {
100                        dir.clone()
101                    }
102                }),
103                src_root: match src {
104                    Some(s) if !s.is_empty() => join(&dir, &s),
105                    _ => dir.clone(),
106                },
107                dir,
108                deps,
109                dev_deps: dev,
110            });
111        } else if name.ends_with(".php") {
112            let is_test = name.ends_with("Test.php")
113                || name.ends_with("_test.php")
114                || rel
115                    .split('/')
116                    .any(|p| matches!(p, "tests" | "test" | "Tests" | "spec"));
117            files.push((
118                rel,
119                if is_test {
120                    FileKind::Test
121                } else {
122                    FileKind::Source
123                },
124            ));
125        }
126    }
127    if !packages.iter().any(|p| p.dir.is_empty()) {
128        packages.push(Package {
129            name: root
130                .file_name()
131                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
132            dir: String::new(),
133            src_root: if root.join("src").is_dir() {
134                "src".into()
135            } else {
136                String::new()
137            },
138            deps: Vec::new(),
139            dev_deps: Vec::new(),
140        });
141    }
142    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
143    files.sort_by(|a, b| a.0.cmp(&b.0));
144    let files = files
145        .into_iter()
146        .map(|(path, kind)| {
147            let package = packages
148                .iter()
149                .enumerate()
150                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
151                .max_by_key(|(_, p)| p.dir.len())
152                .map_or(0, |(i, _)| i);
153            SourceFile {
154                path,
155                package,
156                kind,
157            }
158        })
159        .collect();
160    Ok(Workspace { packages, files })
161}
162
163fn join(dir: &str, rest: &str) -> String {
164    if dir.is_empty() {
165        rest.to_string()
166    } else {
167        format!("{dir}/{rest}")
168    }
169}
170
171// ---- risks and imports -----------------------------------------------------------------------
172
173/// The pattern inside a PCRE string (`'/\w+/u'`, `"#a#i"`, `'~x~'`), without delimiters and flags.
174fn pcre_body(literal: &str) -> Option<&str> {
175    let s = literal.trim_matches(|c| c == '\'' || c == '"');
176    let open = s.chars().next()?;
177    let close = match open {
178        '(' => ')',
179        '{' => '}',
180        '[' => ']',
181        '<' => '>',
182        c if !c.is_alphanumeric() && c != '\\' && !c.is_whitespace() => c,
183        _ => return None,
184    };
185    let end = s.rfind(close)?;
186    (end > 0).then(|| &s[open.len_utf8()..end])
187}
188
189/// The path a `require`/`include` names: `'x.php'` or `__DIR__ . '/x.php'`.
190fn include_target(arg: Node, source: &str) -> Option<String> {
191    let literal = |n: Node| -> Option<String> {
192        matches!(n.kind(), "string" | "encapsed_string")
193            .then(|| {
194                text(n, source)
195                    .trim_matches(|c| c == '\'' || c == '"')
196                    .to_string()
197            })
198            .filter(|s| !s.contains('$'))
199    };
200    if let Some(s) = literal(arg) {
201        return Some(if s.starts_with('/') || s.starts_with('.') {
202            s
203        } else {
204            format!("./{s}")
205        });
206    }
207    if arg.kind() == "binary_expression" {
208        let left = arg.child_by_field_name("left")?;
209        let right = arg.child_by_field_name("right")?;
210        if text(left, source) == "__DIR__" {
211            return literal(right).map(|s| format!(".{s}"));
212        }
213    }
214    None
215}
216
217fn operator<'a>(node: Node, source: &'a str) -> &'a str {
218    node.child_by_field_name("operator").map_or_else(
219        || {
220            let mut cursor = node.walk();
221            node.children(&mut cursor)
222                .find(|c| !c.is_named())
223                .map_or("", |c| text(c, source))
224        },
225        |o| text(o, source),
226    )
227}
228
229const REFLECTION: &[&str] = &[
230    "method_exists",
231    "property_exists",
232    "function_exists",
233    "class_exists",
234    "get_class",
235    "get_object_vars",
236    "call_user_func",
237    "call_user_func_array",
238    "is_callable",
239    "func_get_args",
240    "compact",
241    "extract",
242];
243
244pub fn scan(source: &str) -> FileFacts {
245    let mut facts = FileFacts {
246        loc: syntax::loc(source),
247        ..FileFacts::default()
248    };
249    let Some(tree) = syntax::parse(&language(), source) else {
250        return facts;
251    };
252    let root = tree.root_node();
253    facts.parse_errors = usize::from(root.has_error());
254    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
255        facts
256            .risks
257            .entry(risk)
258            .or_default()
259            .push(syntax::line(node))
260    };
261    syntax::walk(root, |node| match node.kind() {
262        "require_expression"
263        | "require_once_expression"
264        | "include_expression"
265        | "include_once_expression" => {
266            match named_children(node)
267                .into_iter()
268                .next()
269                .and_then(|a| include_target(a, source))
270            {
271                Some(spec) => facts.imports.push(Import {
272                    specifier: spec,
273                    type_only: false,
274                    dynamic: false,
275                }),
276                None => add(&mut facts, Risk::DynamicCode, node),
277            }
278        }
279        "namespace_use_clause" => {
280            let name = node
281                .named_child(0)
282                .map_or_else(|| text(node, source), |n| text(n, source));
283            let prefix = node
284                .parent()
285                .filter(|p| p.kind() == "namespace_use_group")
286                .and_then(|g| g.parent())
287                .and_then(|d| {
288                    named_children(d)
289                        .into_iter()
290                        .find(|n| n.kind() == "namespace_name")
291                })
292                .map(|p| format!("{}\\", text(p, source)))
293                .unwrap_or_default();
294            facts.imports.push(Import {
295                specifier: format!("{prefix}{}", name.trim_start_matches('\\')),
296                type_only: false,
297                dynamic: false,
298            });
299        }
300        "function_call_expression" => {
301            let callee = node
302                .child_by_field_name("function")
303                .map_or("", |f| text(f, source))
304                .trim_start_matches('\\');
305            match callee {
306                "eval" | "create_function" | "assert" => add(&mut facts, Risk::DynamicCode, node),
307                c if REFLECTION.contains(&c) => add(&mut facts, Risk::Reflection, node),
308                c if c.starts_with("preg_") => {
309                    let pattern = node
310                        .child_by_field_name("arguments")
311                        .and_then(|a| named_children(a).into_iter().next())
312                        .and_then(|a| a.named_child(0));
313                    match pattern.filter(|p| matches!(p.kind(), "string" | "encapsed_string")) {
314                        Some(p) if text(p, source).contains('$') => {
315                            add(&mut facts, Risk::DynamicRegex, node)
316                        }
317                        Some(p) => {
318                            if pcre_body(text(p, source)).is_some_and(|b| {
319                                regex_needs_fancy(b, "") || b.contains("(?>") || b.contains("\\K")
320                            }) {
321                                add(&mut facts, Risk::RegexSyntax, node);
322                            }
323                        }
324                        None => add(&mut facts, Risk::DynamicRegex, node),
325                    }
326                }
327                "substr" | "strpos" | "strrpos" | "strlen" | "str_pad" | "substr_replace"
328                | "mb_substr" | "mb_strpos" | "mb_strlen" | "ucfirst" | "strtoupper"
329                | "strtolower" | "str_split" | "wordwrap" => {
330                    add(&mut facts, Risk::StringOffsets, node)
331                }
332                "intdiv" | "fmod" => add(&mut facts, Risk::DivisionSemantics, node),
333                "json_encode" | "json_decode" | "serialize" | "unserialize" => {
334                    add(&mut facts, Risk::Json, node)
335                }
336                "pcntl_fork" | "proc_open" | "curl_multi_exec" => {
337                    add(&mut facts, Risk::Concurrency, node)
338                }
339                "class_alias" | "runkit_function_redefine" | "uopz_set_return" => {
340                    add(&mut facts, Risk::Monkeypatching, node)
341                }
342                "array_map" | "array_filter" | "array_walk" | "array_reduce" | "usort"
343                | "uasort" | "uksort" => {
344                    facts.loops += 1;
345                    add(&mut facts, Risk::Callbacks, node);
346                }
347                "sort" | "asort" | "ksort" | "array_unique" | "array_keys" | "array_values" => {
348                    add(&mut facts, Risk::OrderedCollections, node)
349                }
350                _ => {}
351            }
352        }
353        "object_creation_expression" => {
354            let class = text(node, source);
355            if class.contains("Reflection") {
356                add(&mut facts, Risk::Reflection, node);
357            } else if class.contains("Fiber") || class.contains("parallel\\") {
358                add(&mut facts, Risk::Concurrency, node);
359            }
360        }
361        "dynamic_variable_name" => add(&mut facts, Risk::Reflection, node),
362        "method_declaration" => {
363            let name = node
364                .child_by_field_name("name")
365                .map_or("", |n| text(n, source));
366            if matches!(
367                name,
368                "__call" | "__callStatic" | "__get" | "__set" | "__isset" | "__unset"
369            ) {
370                add(&mut facts, Risk::Reflection, node);
371            }
372        }
373        "class_declaration" | "interface_declaration" | "trait_declaration" => {
374            if named_children(node)
375                .iter()
376                .any(|c| c.kind() == "base_clause")
377            {
378                add(&mut facts, Risk::ClassInheritance, node);
379            }
380        }
381        "use_declaration" => add(&mut facts, Risk::ClassInheritance, node),
382        "binary_expression" => match operator(node, source) {
383            "/" => add(&mut facts, Risk::NumberSemantics, node),
384            "%" => add(&mut facts, Risk::DivisionSemantics, node),
385            "**" | "<<" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
386            "==" | "!=" | "<>" | "<=>" => add(&mut facts, Risk::DynamicTyping, node),
387            _ => {}
388        },
389        "array_creation_expression" => add(&mut facts, Risk::OrderedCollections, node),
390        "throw_expression" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
391        "yield_expression" => add(&mut facts, Risk::Generators, node),
392        "anonymous_function" | "anonymous_function_creation_expression" | "arrow_function" => {
393            add(&mut facts, Risk::Callbacks, node)
394        }
395        "null" => add(&mut facts, Risk::NullReferences, node),
396        "foreach_statement" | "for_statement" | "while_statement" | "do_statement" => {
397            facts.loops += 1
398        }
399        _ => {}
400    });
401    facts
402}
403
404/// Namespace roots of common Composer packages: `use GuzzleHttp\Client` needs `guzzlehttp/guzzle`.
405const NAMESPACE_PACKAGES: &[(&str, &str)] = &[
406    ("GuzzleHttp", "guzzlehttp/guzzle"),
407    ("Monolog", "monolog/monolog"),
408    ("Carbon", "nesbot/carbon"),
409    ("Ramsey\\Uuid", "ramsey/uuid"),
410    ("Illuminate", "laravel/framework"),
411    ("Doctrine\\ORM", "doctrine/orm"),
412    ("Doctrine\\DBAL", "doctrine/dbal"),
413    ("Twig", "twig/twig"),
414    ("League\\CommonMark", "league/commonmark"),
415    ("League\\Csv", "league/csv"),
416    ("League\\Flysystem", "league/flysystem"),
417    ("Dotenv", "vlucas/phpdotenv"),
418    ("Firebase\\JWT", "firebase/php-jwt"),
419    ("Predis", "predis/predis"),
420    ("Slim", "slim/slim"),
421    ("PHPUnit", "phpunit/phpunit"),
422    ("Psr\\Log", "psr/log"),
423    ("Psr\\Http\\Message", "psr/http-message"),
424    ("Respect\\Validation", "respect/validation"),
425    ("Brick\\Math", "brick/math"),
426];
427
428/// The Composer package a namespace belongs to: `Symfony\Component\Yaml\Yaml` is
429/// `symfony/yaml`; otherwise from [`NAMESPACE_PACKAGES`], else the namespace root.
430fn package_of(spec: &str) -> String {
431    if let Some(rest) = spec.strip_prefix("Symfony\\Component\\") {
432        let component = rest.split('\\').next().unwrap_or(rest);
433        let mut kebab = String::new();
434        for (i, c) in component.chars().enumerate() {
435            if c.is_uppercase() && i > 0 {
436                kebab.push('-');
437            }
438            kebab.extend(c.to_lowercase());
439        }
440        return format!("symfony/{kebab}");
441    }
442    NAMESPACE_PACKAGES
443        .iter()
444        .find(|(ns, _)| spec == *ns || spec.starts_with(&format!("{ns}\\")))
445        .map_or_else(
446            || spec.split('\\').next().unwrap_or(spec).to_string(),
447            |(_, p)| (*p).to_string(),
448        )
449}
450
451pub fn resolve(
452    from: &str,
453    spec: &str,
454    index: &HashMap<&str, usize>,
455    ws: &Workspace,
456) -> super::Resolution {
457    if spec.starts_with("./") || spec.starts_with("../") || spec.ends_with(".php") {
458        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
459        let rel = spec.trim_start_matches("./");
460        if let Some(path) = normalize(&join(dir, rel))
461            && let Some(i) = index.get(path.as_str())
462        {
463            return super::Resolution::File(*i);
464        }
465        return super::Resolution::Unresolved;
466    }
467    // PSR-4: `App\Text\Slug` is `<src>/Text/Slug.php` for the `App\` prefix; the prefix is
468    // unknown here, so try each tail of the namespace under each package's source root.
469    let parts: Vec<&str> = spec.split('\\').filter(|p| !p.is_empty()).collect();
470    for p in &ws.packages {
471        for skip in 0..parts.len() {
472            let candidate = join(&p.src_root, &format!("{}.php", parts[skip..].join("/")));
473            if let Some(i) = index.get(candidate.as_str()) {
474                return super::Resolution::File(*i);
475            }
476        }
477    }
478    if parts.len() <= 1 {
479        return super::Resolution::Stdlib;
480    }
481    super::Resolution::External(package_of(spec))
482}
483
484fn normalize(path: &str) -> Option<String> {
485    let mut parts: Vec<&str> = Vec::new();
486    for part in path.split('/') {
487        match part {
488            "" | "." => {}
489            ".." => {
490                parts.pop()?;
491            }
492            _ => parts.push(part),
493        }
494    }
495    Some(parts.join("/"))
496}
497
498/// Rust counterparts of common Composer packages.
499pub fn lookup(package: &str) -> Option<CrateMatch> {
500    crate::crates::find("php", package)
501}
502
503// ---- exports ---------------------------------------------------------------------------------
504
505/// A PHP type (native or phpdoc: `?int`, `string|null`, `int[]`, `array<string, int>`,
506/// `list<string>`) in the dialect.
507pub fn php_to_ts(t: &str) -> String {
508    let t = t.trim().trim_start_matches('\\');
509    if let Some(inner) = t.strip_prefix('?') {
510        return format!("{} | undefined", php_to_ts(inner));
511    }
512    let parts = split_top(t, '|');
513    if parts.len() > 1 {
514        let mapped: Vec<String> = parts.iter().map(|p| php_to_ts(p)).collect();
515        return mapped.join(" | ");
516    }
517    if let Some(inner) = t.strip_suffix("[]") {
518        let inner = php_to_ts(inner);
519        return if inner.contains(' ') {
520            format!("({inner})[]")
521        } else {
522            format!("{inner}[]")
523        };
524    }
525    for generic in [
526        "list<",
527        "array<",
528        "iterable<",
529        "non-empty-list<",
530        "non-empty-array<",
531    ] {
532        if let Some(inner) = t.strip_prefix(generic).and_then(|r| r.strip_suffix('>')) {
533            let args = split_top(inner, ',');
534            return match args.as_slice() {
535                [v] => format!("{}[]", php_to_ts(v)),
536                [k, v] if php_to_ts(k) == "string" => format!("Record<string, {}>", php_to_ts(v)),
537                [k, v] if php_to_ts(k) == "int" => format!("{}[]", php_to_ts(v)),
538                _ => "unknown".into(),
539            };
540        }
541    }
542    match t.to_ascii_lowercase().as_str() {
543        "string" | "non-empty-string" | "class-string" | "numeric-string" => "string".into(),
544        "int" | "integer" | "positive-int" | "negative-int" | "non-negative-int" => "int".into(),
545        "float" | "double" => "number".into(),
546        "bool" | "boolean" | "true" | "false" => "boolean".into(),
547        "null" | "void" => "undefined".into(),
548        "array" | "iterable" => "unknown[]".into(),
549        _ => "unknown".into(),
550    }
551}
552
553fn split_top(text: &str, sep: char) -> Vec<String> {
554    let mut out = Vec::new();
555    let mut depth = 0i32;
556    let mut current = String::new();
557    for c in text.chars() {
558        match c {
559            '<' | '{' | '(' | '[' => depth += 1,
560            '>' | '}' | ')' | ']' => depth -= 1,
561            _ if c == sep && depth == 0 => {
562                out.push(current.trim().to_string());
563                current.clear();
564                continue;
565            }
566            _ => {}
567        }
568        current.push(c);
569    }
570    if !current.trim().is_empty() {
571        out.push(current.trim().to_string());
572    }
573    out
574}
575
576/// The phpdoc block right above `node`, one tag per entry (`@param string $s`).
577fn phpdoc(node: Node, source: &str) -> Vec<String> {
578    let Some(prev) = node.prev_named_sibling().filter(|p| p.kind() == "comment") else {
579        return Vec::new();
580    };
581    let doc = text(prev, source);
582    if !doc.starts_with("/**") {
583        return Vec::new();
584    }
585    doc.trim_start_matches("/**")
586        .trim_end_matches("*/")
587        .split('@')
588        .skip(1)
589        .map(|tag| {
590            format!(
591                "@{}",
592                tag.lines()
593                    .map(|l| l.trim().trim_start_matches('*').trim())
594                    .collect::<Vec<_>>()
595                    .join(" ")
596                    .trim()
597            )
598        })
599        .collect()
600}
601
602/// The dialect type of a literal default (`'-'`, `0`, `1.5`, `true`, `[]`).
603fn literal_type(value: &str) -> Option<&'static str> {
604    let v = value.trim();
605    if v.starts_with('"') || v.starts_with('\'') {
606        Some("string")
607    } else if v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("false") {
608        Some("boolean")
609    } else if v.parse::<i64>().is_ok() {
610        Some("int")
611    } else if v.parse::<f64>().is_ok() {
612        Some("number")
613    } else if v.starts_with('[') {
614        Some("unknown[]")
615    } else {
616        None
617    }
618}
619
620fn function_fn(
621    path: &str,
622    receiver: &str,
623    sep: &str,
624    node: Node,
625    source: &str,
626) -> Option<ExportedFn> {
627    let name = text(node.child_by_field_name("name")?, source).to_string();
628    let doc = phpdoc(node, source);
629    let doc_param = |p: &str| {
630        doc.iter().find_map(|tag| {
631            let rest = tag.strip_prefix("@param ")?;
632            let mut words = rest.split_whitespace();
633            let t = words.next()?;
634            (words.next()? == format!("${p}")).then(|| php_to_ts(t))
635        })
636    };
637    let returns = node
638        .child_by_field_name("return_type")
639        .map(|t| php_to_ts(text(t, source)))
640        .filter(|t| t != "unknown")
641        .or_else(|| {
642            doc.iter().find_map(|tag| {
643                let t = tag.strip_prefix("@return ")?.split_whitespace().next()?;
644                Some(php_to_ts(t))
645            })
646        })
647        .unwrap_or_else(|| "unknown".into());
648    let mut blocker = None;
649    if name.starts_with("__") {
650        blocker = Some(format!("`{name}` is a magic method"));
651    }
652    let mut params = Vec::new();
653    let mut signature = String::new();
654    if let Some(list) = node.child_by_field_name("parameters") {
655        signature = text(list, source)
656            .trim_start_matches('(')
657            .trim_end_matches(')')
658            .to_string();
659        for p in named_children(list) {
660            let pname = p
661                .child_by_field_name("name")
662                .map(|n| text(n, source).trim_start_matches('$').to_string())
663                .unwrap_or_default();
664            match p.kind() {
665                "simple_parameter" => {}
666                "variadic_parameter" => {
667                    blocker.get_or_insert_with(|| "takes `...$args`".into());
668                    continue;
669                }
670                _ => {
671                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
672                    continue;
673                }
674            }
675            if named_children(p)
676                .iter()
677                .any(|c| c.kind() == "reference_modifier")
678                || text(p, source).contains("&$")
679            {
680                blocker.get_or_insert_with(|| format!("takes `${pname}` by reference"));
681            }
682            let declared = p.child_by_field_name("type").map(|t| text(t, source));
683            if declared.is_some_and(|t| t.contains("callable") || t.contains("Closure")) {
684                blocker.get_or_insert_with(|| format!("takes a callable `${pname}`"));
685            }
686            let value = p
687                .child_by_field_name("default_value")
688                .map(|v| text(v, source).to_string());
689            let mut ts_type = declared
690                .map(php_to_ts)
691                .filter(|t| t != "unknown")
692                .or_else(|| doc_param(&pname))
693                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
694                .unwrap_or_else(|| "unknown".into());
695            if value
696                .as_deref()
697                .is_some_and(|v| v.eq_ignore_ascii_case("null"))
698                && !ts_type.contains("undefined")
699            {
700                ts_type = format!("{ts_type} | undefined");
701            }
702            params.push(Param {
703                name: pname,
704                ts_type,
705                optional: value.is_some(),
706                default: value,
707                ..Default::default()
708            });
709        }
710    }
711    if let Some(body) = node.child_by_field_name("body") {
712        let mut yields = false;
713        syntax::walk(body, |n| yields |= n.kind() == "yield_expression");
714        if yields {
715            blocker.get_or_insert_with(|| "is a generator (`yield`)".into());
716        }
717    }
718    let prefix = if receiver.is_empty() {
719        String::new()
720    } else {
721        format!("{receiver}{sep}")
722    };
723    Some(ExportedFn {
724        name: name.clone(),
725        file: path.to_string(),
726        line: syntax::line(node),
727        params,
728        returns,
729        prototype: Some(format!("{prefix}{name}({signature})")),
730        blocker,
731        ..Default::default()
732    })
733}
734
735/// Functions (`Ns\name(...)`) and public static methods of classes (`Ns\Class::name(...)`).
736pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
737    if !path.ends_with(".php") {
738        return Vec::new();
739    }
740    let Some(tree) = syntax::parse(&language(), source) else {
741        return Vec::new();
742    };
743    let mut out = Vec::new();
744    let mut namespace = String::new();
745    let visit = |items: Vec<Node>, namespace: &mut String, out: &mut Vec<ExportedFn>| {
746        for item in items {
747            match item.kind() {
748                "namespace_definition" => {
749                    *namespace = item
750                        .child_by_field_name("name")
751                        .map(|n| text(n, source).to_string())
752                        .unwrap_or_default();
753                }
754                "function_definition" => {
755                    out.extend(function_fn(path, namespace, "\\", item, source));
756                }
757                "class_declaration" => {
758                    if named_children(item)
759                        .iter()
760                        .any(|c| c.kind() == "abstract_modifier")
761                    {
762                        continue;
763                    }
764                    let Some(class) = item.child_by_field_name("name") else {
765                        continue;
766                    };
767                    let class = text(class, source);
768                    let receiver = if namespace.is_empty() {
769                        class.to_string()
770                    } else {
771                        format!("{namespace}\\{class}")
772                    };
773                    for method in item
774                        .child_by_field_name("body")
775                        .map(named_children)
776                        .unwrap_or_default()
777                        .into_iter()
778                        .filter(|m| m.kind() == "method_declaration")
779                    {
780                        let mods: Vec<&str> = named_children(method)
781                            .iter()
782                            .filter(|c| c.kind().ends_with("_modifier"))
783                            .map(|c| text(*c, source))
784                            .collect();
785                        let public = !mods.iter().any(|m| matches!(*m, "private" | "protected"));
786                        if public && mods.contains(&"static") {
787                            out.extend(function_fn(path, &receiver, "::", method, source));
788                        }
789                    }
790                }
791                _ => {}
792            }
793        }
794    };
795    let root = tree.root_node();
796    for item in named_children(root) {
797        if item.kind() == "namespace_definition"
798            && let Some(body) = item.child_by_field_name("body")
799        {
800            namespace = item
801                .child_by_field_name("name")
802                .map(|n| text(n, source).to_string())
803                .unwrap_or_default();
804            visit(named_children(body), &mut namespace, &mut out);
805        } else {
806            visit(vec![item], &mut namespace, &mut out);
807        }
808    }
809    out.sort_by_key(|f| f.line);
810    out
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816
817    const SRC: &str = r#"<?php
818declare(strict_types=1);
819namespace App\Text;
820use App\Util\Str;
821use GuzzleHttp\Client;
822use Symfony\Component\Yaml\Yaml;
823require_once __DIR__ . '/helpers.php';
824
825/**
826 * @param string $s
827 * @param list<string> $stop
828 * @return string
829 */
830function slugify(string $s, $stop = [], string $sep = '-', ?int $max = null): string {
831    if ($s === '') { throw new \InvalidArgumentException("empty"); }
832    $x = intdiv(7, 2) % 3;
833    return strtolower(preg_replace('/(?<=a)b/u', $sep, $s));
834}
835
836function words($text) { foreach (explode(' ', $text) as $w) { yield $w; } }
837
838final class Words extends Base {
839    public static function count(string $s, int ...$rest): int { return str_word_count($s); }
840    public static function scale($x, float $factor = 1.5) { return $x * $factor; }
841    private static function hidden() {}
842    public function instance() {}
843}
844eval('1;');
845"#;
846
847    #[test]
848    fn maps_php_types() {
849        assert_eq!(php_to_ts("?int"), "int | undefined");
850        assert_eq!(php_to_ts("string|null"), "string | undefined");
851        assert_eq!(php_to_ts("int[]"), "int[]");
852        assert_eq!(php_to_ts("array<string, int>"), "Record<string, int>");
853        assert_eq!(php_to_ts("list<float>"), "number[]");
854        assert_eq!(php_to_ts("\\DateTime"), "unknown");
855    }
856
857    #[test]
858    fn finds_functions_and_static_methods() {
859        let fns = exports("src/Text/slug.php", SRC);
860        let protos: Vec<&str> = fns
861            .iter()
862            .map(|f| f.prototype.as_deref().unwrap_or(""))
863            .collect();
864        assert_eq!(
865            protos,
866            [
867                "App\\Text\\slugify(string $s, $stop = [], string $sep = '-', ?int $max = null)",
868                "App\\Text\\words($text)",
869                "App\\Text\\Words::count(string $s, int ...$rest)",
870                "App\\Text\\Words::scale($x, float $factor = 1.5)",
871            ]
872        );
873        let slug = &fns[0];
874        let types: Vec<&str> = slug.params.iter().map(|p| p.ts_type.as_str()).collect();
875        assert_eq!(types, ["string", "string[]", "string", "int | undefined"]);
876        assert_eq!(slug.returns, "string");
877        assert!(slug.blocker.is_none());
878        assert!(fns[1].blocker.as_deref().unwrap().contains("generator"));
879        assert!(fns[2].blocker.as_deref().unwrap().contains("...$args"));
880        assert_eq!(fns[3].params[1].ts_type, "number");
881    }
882
883    #[test]
884    fn resolves_import_names_from_a_group_use() {
885        let facts = scan(
886            r"<?php
887namespace App;
888use Vendor\Library\{One, Two as Alias, function helpers\trim_value};
889use Other\Three;
890",
891        );
892        assert_eq!(facts.parse_errors, 0);
893        assert_eq!(
894            facts
895                .imports
896                .iter()
897                .map(|i| i.specifier.as_str())
898                .collect::<Vec<_>>(),
899            [
900                "Vendor\\Library\\One",
901                "Vendor\\Library\\Two",
902                "Vendor\\Library\\helpers\\trim_value",
903                "Other\\Three"
904            ]
905        );
906    }
907
908    #[test]
909    fn scans_imports_and_risks() {
910        let facts = scan(SRC);
911        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
912        assert_eq!(
913            specs,
914            [
915                "App\\Util\\Str",
916                "GuzzleHttp\\Client",
917                "Symfony\\Component\\Yaml\\Yaml",
918                "./helpers.php"
919            ]
920        );
921        for risk in [
922            Risk::Exceptions,
923            Risk::RegexSyntax,
924            Risk::DivisionSemantics,
925            Risk::Generators,
926            Risk::ClassInheritance,
927            Risk::DynamicCode,
928            Risk::StringOffsets,
929        ] {
930            assert!(
931                facts.risks.contains_key(&risk),
932                "{risk:?}: {:?}",
933                facts.risks
934            );
935        }
936        assert_eq!(package_of("GuzzleHttp\\Client"), "guzzlehttp/guzzle");
937        assert_eq!(
938            package_of("Symfony\\Component\\HttpFoundation\\Request"),
939            "symfony/http-foundation"
940        );
941        assert_eq!(pcre_body("'#a+#i'"), Some("a+"));
942        assert_eq!(pcre_body("'{x}u'"), Some("x"));
943    }
944
945    #[test]
946    fn reads_composer() {
947        let (name, deps, dev, src) = composer(
948            r#"{"name": "acme/tool", "require": {"php": ">=8.1", "ext-json": "*", "guzzlehttp/guzzle": "^7"},
949               "require-dev": {"phpunit/phpunit": "^10"}, "autoload": {"psr-4": {"Acme\\": "src/"}}}"#,
950        );
951        assert_eq!(name.as_deref(), Some("acme/tool"));
952        assert_eq!(deps, ["guzzlehttp/guzzle"]);
953        assert_eq!(dev, ["phpunit/phpunit"]);
954        assert_eq!(src.as_deref(), Some("src"));
955    }
956}