Skip to main content

mortise_core/
surface.rs

1//! The public surface of a module: the one a team accepted, and a scan that proposes one.
2//!
3//! The surface is everything of a module that something outside it may use: classes
4//! for other modules, routes for HTTP clients, console commands for the command line
5//! and the scheduler. The accepted surface is the `surface` key of the module's
6//! `module.json`, which the package command `module:surface` writes (P6). The scan
7//! reads the files of the module and proposes a list. Neither writes anything.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14use crate::app::AppSnapshot;
15use crate::modules::kind::{Kinds, TESTS};
16use crate::modules::layout::Layout;
17use crate::modules::module::{artisan_command, command_of, files_of, is_php};
18use crate::php::{DeclaredKind, analyze};
19
20/// The folder kind of the package's event generator.
21const EVENTS: &str = "Events";
22
23/// The accepted public surface of a module: the `surface` key of its `module.json`.
24///
25/// The package stores each list deduplicated and sorted by byte order. A module whose
26/// `module.json` has no `surface` key has no accepted surface; one with empty lists
27/// offers nothing.
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct AcceptedSurface {
31    /// Full class names, without a leading backslash.
32    #[serde(default)]
33    pub classes: Vec<String>,
34    /// Route URIs or patterns, as the package stores them.
35    #[serde(default)]
36    pub routes: Vec<String>,
37    /// Console command names.
38    #[serde(default)]
39    pub commands: Vec<String>,
40}
41
42impl AcceptedSurface {
43    /// The surface of a `module.json` document. `None` when it has no `surface` key, or
44    /// when the package would refuse it: the rule then uses the folder list. The package
45    /// reads an object of the lists `classes`, `routes` and `commands`, each an array of
46    /// strings, and refuses an entry that `--set` would not store as it is.
47    pub(crate) fn of_manifest(manifest: &serde_json::Value) -> Option<Self> {
48        // Serde also reads a struct from a positional array; the package does not.
49        let surface = manifest
50            .get("surface")
51            .filter(|surface| surface.is_object())?;
52        let surface: Self = serde_json::from_value(surface.clone()).ok()?;
53        let stored =
54            |list: &[String], valid: fn(&str) -> bool| list.iter().all(|entry| valid(entry));
55        (stored(&surface.classes, is_class_name)
56            && stored(&surface.routes, |route| {
57                stored_route(route).as_deref() == Some(route)
58            })
59            && stored(&surface.commands, is_command_name))
60        .then_some(surface)
61    }
62
63    /// The surface stored in the `module.json` file at `path`. `None` when the file
64    /// cannot be read, or holds no surface the package would read.
65    pub fn of_file(path: &std::path::Path) -> Option<Self> {
66        let text = std::fs::read(path).ok()?;
67        Self::of_manifest(&serde_json::from_slice(&text).ok()?)
68    }
69
70    /// The surface as the package stores it: each list deduplicated and sorted by byte
71    /// order. Classes lose a leading backslash and are the same in any case: the first
72    /// spelling is kept.
73    pub fn normalized(mut self) -> Self {
74        let mut seen = BTreeSet::new();
75        self.classes = self
76            .classes
77            .into_iter()
78            .map(|class| class.trim_start_matches('\\').to_owned())
79            .filter(|class| seen.insert(class.to_lowercase()))
80            .collect();
81        self.routes = self
82            .routes
83            .into_iter()
84            .map(|route| stored_route(&route).unwrap_or(route))
85            .collect();
86        for list in [&mut self.classes, &mut self.routes, &mut self.commands] {
87            list.sort();
88            list.dedup();
89        }
90        self
91    }
92
93    /// The list an entry of this kind belongs to.
94    fn list_of(&mut self, kind: SurfaceKind) -> &mut Vec<String> {
95        match kind {
96            SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
97                &mut self.classes
98            }
99            SurfaceKind::Route => &mut self.routes,
100            SurfaceKind::Command => &mut self.commands,
101        }
102    }
103
104    /// How many entries the surface has.
105    pub fn entries(&self) -> usize {
106        self.classes.len() + self.routes.len() + self.commands.len()
107    }
108
109    /// True when the class is in the surface. PHP class names are the same in any case.
110    pub fn has_class(&self, class: &str) -> bool {
111        self.classes.iter().any(|listed| same_class(listed, class))
112    }
113
114    /// True when a route of the module is under a route of the surface.
115    fn covers(&self, uri: &str) -> bool {
116        self.routes.iter().any(|route| pattern_matches(route, uri))
117    }
118
119    /// True when the entry of a proposal is in the surface: a class in any case, a
120    /// route and a command exactly.
121    pub fn has(&self, entry: &SurfaceEntry) -> bool {
122        match entry.kind {
123            SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
124                self.has_class(&entry.name)
125            }
126            SurfaceKind::Route => self.routes.contains(&entry.name),
127            SurfaceKind::Command => self.commands.contains(&entry.name),
128        }
129    }
130
131    /// The surface with the differences that are taken: a new entry added, an entry
132    /// that is gone removed.
133    pub fn with_differences(&self, differences: &[Difference]) -> Self {
134        let mut surface = self.clone();
135        for difference in differences.iter().filter(|difference| difference.taken) {
136            let entry = &difference.entry;
137            let list = surface.list_of(entry.kind);
138            if difference.new {
139                list.push(entry.name.clone());
140            } else {
141                // A class is the same in any case; the other lists are exact.
142                let class = !matches!(entry.kind, SurfaceKind::Route | SurfaceKind::Command);
143                list.retain(|listed| {
144                    if class {
145                        !same_class(listed, &entry.name)
146                    } else {
147                        listed != &entry.name
148                    }
149                });
150            }
151        }
152        surface.normalized()
153    }
154
155    /// The JSON object that `module:surface <module> --set --stdin` reads.
156    pub fn to_stdin(&self) -> String {
157        serde_json::to_string(self).expect("a surface is plain data")
158    }
159}
160
161/// The package command that stores `surface` as the accepted surface of `module`.
162/// Its standard input is [`AcceptedSurface::to_stdin`].
163pub fn surface_args(module: &str) -> Vec<String> {
164    ["module:surface", module, "--set", "--stdin", "--json"]
165        .map(str::to_owned)
166        .to_vec()
167}
168
169/// What `module:surface --json` prints: the surface it stored, or why it stored nothing.
170#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
171pub struct SurfaceAnswer {
172    pub module: String,
173    /// The surface as stored. `None` with errors.
174    #[serde(default)]
175    pub surface: Option<AcceptedSurface>,
176    /// False when the stored surface was the same already.
177    #[serde(default)]
178    pub changed: bool,
179    #[serde(default)]
180    pub errors: Vec<SurfaceProblem>,
181}
182
183/// One reason `module:surface` stored nothing.
184#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
185pub struct SurfaceProblem {
186    pub message: String,
187}
188
189/// One difference between a later scan and the accepted surface (S5.9).
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct Difference {
192    /// The entry of the proposal, for a new one, or the accepted entry that is gone.
193    pub entry: SurfaceEntry,
194    /// True when the scan proposes it and the surface lacks it. False when the surface
195    /// has it and the module no longer does.
196    pub new: bool,
197    /// True when accepting the differences takes this one. The developer can change it.
198    pub taken: bool,
199}
200
201/// What an entry of a public surface is.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
203pub enum SurfaceKind {
204    /// An interface the module declares.
205    Contract,
206    /// A class in the module's events folder.
207    Event,
208    /// A class that another module uses and that is neither a contract nor an event.
209    OtherClass,
210    /// The routes of the module under one prefix.
211    Route,
212    /// A console command of the module.
213    Command,
214}
215
216/// One thing a module offers to the outside.
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct SurfaceEntry {
219    pub kind: SurfaceKind,
220    /// The full class name, the route pattern or the command name.
221    pub name: String,
222    /// For a class: the kind of the folder its file is in, such as `Contracts` or `Models`.
223    pub folder: String,
224    /// For a class: the modules that use it today, each with how many of its files do.
225    pub used_by: Vec<(String, usize)>,
226    /// For a route pattern: how many routes it stands for.
227    pub routes: usize,
228    /// For a command: the schedule of a scheduled task that runs it, as the app wrote it.
229    pub schedule: Option<String>,
230    /// True when the entry is in the proposal. The developer can change it.
231    pub proposed: bool,
232    /// True for an entry the developer added by hand.
233    pub by_hand: bool,
234}
235
236impl SurfaceEntry {
237    fn new(kind: SurfaceKind, name: String) -> Self {
238        Self {
239            kind,
240            name,
241            folder: String::new(),
242            used_by: Vec::new(),
243            routes: 0,
244            schedule: None,
245            proposed: true,
246            by_hand: false,
247        }
248    }
249
250    /// How many files outside the module use the entry.
251    pub fn used_files(&self) -> usize {
252        self.used_by.iter().map(|(_, files)| files).sum()
253    }
254}
255
256/// What a name typed by hand turned out to be.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub enum Typed {
259    /// A class the module declares, in this folder.
260    Class { folder: String },
261    /// A console command of the module.
262    Command,
263    /// A route pattern that stands for this many routes of the module.
264    Route { routes: usize },
265    /// It is in the proposal already.
266    Listed,
267    /// Nothing in the module has this name.
268    Unknown,
269}
270
271/// What a scan found, as a list the developer can change.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273pub struct Proposal {
274    pub module: String,
275    /// Contracts, events, other classes, routes, then commands. In each kind what is
276    /// used from outside comes first.
277    pub entries: Vec<SurfaceEntry>,
278    /// False when no routes were given to the scan: no environment is connected.
279    pub routes_read: bool,
280    /// Every class the module declares outside its tests, with the kind of its folder.
281    declared: BTreeMap<String, String>,
282    /// The names of the module's console commands.
283    commands: BTreeSet<String>,
284    /// The URIs of the module's routes.
285    uris: Vec<String>,
286}
287
288impl Proposal {
289    /// How many entries the scan found or the developer added.
290    pub fn found(&self) -> usize {
291        self.entries.len()
292    }
293
294    /// How many entries are in the proposal.
295    pub fn proposed(&self) -> usize {
296        self.entries.iter().filter(|entry| entry.proposed).count()
297    }
298
299    /// The entries of one kind.
300    pub fn of(&self, kind: SurfaceKind) -> impl Iterator<Item = (usize, &SurfaceEntry)> {
301        self.entries
302            .iter()
303            .enumerate()
304            .filter(move |(_, entry)| entry.kind == kind)
305    }
306
307    /// Says what a name typed by hand is in this module.
308    pub fn check(&self, typed: &str) -> Typed {
309        let typed = typed.trim().trim_start_matches('\\');
310        if typed.is_empty() {
311            return Typed::Unknown;
312        }
313        if self.entries.iter().any(|entry| entry.name == typed) {
314            return Typed::Listed;
315        }
316        if let Some(folder) = self.declared.get(typed) {
317            return Typed::Class {
318                folder: folder.clone(),
319            };
320        }
321        if self.commands.contains(typed) {
322            return Typed::Command;
323        }
324        let routes = self
325            .uris
326            .iter()
327            .filter(|uri| pattern_matches(typed, uri))
328            .count();
329        if routes > 0 {
330            Typed::Route { routes }
331        } else {
332            Typed::Unknown
333        }
334    }
335
336    /// Adds an entry by hand, when the name is something of the module. Returns
337    /// false when it is not, or when it is listed already.
338    pub fn add(&mut self, typed: &str) -> bool {
339        let name = typed.trim().trim_start_matches('\\').to_owned();
340        let mut entry = match self.check(&name) {
341            Typed::Class { folder } => {
342                let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, name);
343                entry.folder = folder;
344                entry
345            }
346            Typed::Command => SurfaceEntry::new(SurfaceKind::Command, name),
347            Typed::Route { routes } => {
348                let mut entry = SurfaceEntry::new(SurfaceKind::Route, name);
349                entry.routes = routes;
350                entry
351            }
352            Typed::Listed | Typed::Unknown => return false,
353        };
354        entry.by_hand = true;
355        self.insert(entry);
356        true
357    }
358
359    /// Puts an entry after the last entry of its kind, so that the kinds stay together.
360    fn insert(&mut self, entry: SurfaceEntry) {
361        let at = self
362            .entries
363            .iter()
364            .rposition(|other| other.kind <= entry.kind)
365            .map_or(0, |last| last + 1);
366        self.entries.insert(at, entry);
367    }
368
369    /// Takes over what the developer chose in an earlier proposal, where the entry
370    /// still exists: what was left out stays out, what was added by hand stays in.
371    pub fn keep_choices_of(&mut self, earlier: &Proposal) {
372        for entry in &earlier.entries {
373            let same = self
374                .entries
375                .iter_mut()
376                .find(|other| other.kind == entry.kind && other.name == entry.name);
377            match same {
378                Some(same) => same.proposed = entry.proposed,
379                None if entry.by_hand => {
380                    if self.add(&entry.name)
381                        && let Some(added) = self
382                            .entries
383                            .iter_mut()
384                            .find(|other| other.name == entry.name)
385                    {
386                        added.proposed = entry.proposed;
387                    }
388                }
389                None => {}
390            }
391        }
392    }
393
394    /// The entries that are in the proposal, as a surface to store.
395    pub fn surface(&self) -> AcceptedSurface {
396        let mut surface = AcceptedSurface::default();
397        for entry in self.entries.iter().filter(|entry| entry.proposed) {
398            let list = surface.list_of(entry.kind);
399            list.push(entry.name.clone());
400        }
401        surface.normalized()
402    }
403
404    /// Checks what the accepted surface has and nothing else, for a change of it (S5.8).
405    /// An accepted entry that the scan did not list is added, when the module has it.
406    /// An accepted route stays when the routes were not read: the scan cannot say
407    /// whether the module still has it.
408    pub fn take_choices_of(&mut self, accepted: &AcceptedSurface) {
409        for entry in &mut self.entries {
410            entry.proposed = accepted.has(entry);
411        }
412        let names = accepted
413            .classes
414            .iter()
415            .chain(&accepted.routes)
416            .chain(&accepted.commands);
417        for name in names {
418            if self.add(name)
419                && let Some(added) = self.entries.iter_mut().find(|entry| &entry.name == name)
420            {
421                added.by_hand = false;
422            }
423        }
424        if !self.routes_read {
425            for route in &accepted.routes {
426                if !self
427                    .entries
428                    .iter()
429                    .any(|entry| entry.kind == SurfaceKind::Route && &entry.name == route)
430                {
431                    self.insert(SurfaceEntry::new(SurfaceKind::Route, route.clone()));
432                }
433            }
434        }
435    }
436
437    /// What differs between this scan and the accepted surface (S5.9): what the scan
438    /// proposes that the surface lacks, then what the surface has that the module no
439    /// longer has. A route pattern is new only when the surface does not cover one of
440    /// its routes. A route is gone only when the routes were read.
441    pub fn differences(&self, accepted: &AcceptedSurface) -> Vec<Difference> {
442        let lacks = |entry: &SurfaceEntry| match entry.kind {
443            SurfaceKind::Route => self
444                .uris
445                .iter()
446                .any(|uri| pattern_matches(&entry.name, uri) && !accepted.covers(uri)),
447            _ => !accepted.has(entry),
448        };
449        let mut differences: Vec<Difference> = self
450            .entries
451            .iter()
452            .filter(|entry| entry.proposed && lacks(entry))
453            .map(|entry| Difference {
454                entry: entry.clone(),
455                new: true,
456                taken: true,
457            })
458            .collect();
459        let gone = |kind: SurfaceKind, name: &String| Difference {
460            entry: SurfaceEntry::new(kind, name.clone()),
461            new: false,
462            taken: true,
463        };
464        for class in &accepted.classes {
465            if !self
466                .declared
467                .keys()
468                .any(|declared| same_class(declared, class))
469            {
470                differences.push(gone(SurfaceKind::OtherClass, class));
471            }
472        }
473        if self.routes_read {
474            for route in &accepted.routes {
475                if !self.uris.iter().any(|uri| pattern_matches(route, uri)) {
476                    differences.push(gone(SurfaceKind::Route, route));
477                }
478            }
479        }
480        for command in &accepted.commands {
481            if !self.commands.contains(command) {
482                differences.push(gone(SurfaceKind::Command, command));
483            }
484        }
485        differences
486    }
487
488    /// The proposal as text, for a place the package does not give yet: the entries
489    /// that are in it, by kind.
490    pub fn as_text(&self) -> String {
491        let mut text = format!("Public surface of {}, proposed by Mortise\n", self.module);
492        let groups = [
493            (SurfaceKind::Contract, "Contracts"),
494            (SurfaceKind::Event, "Events"),
495            (SurfaceKind::OtherClass, "Other classes"),
496            (SurfaceKind::Route, "Routes"),
497            (SurfaceKind::Command, "Console commands"),
498        ];
499        for (kind, title) in groups {
500            let names: Vec<&str> = self
501                .of(kind)
502                .filter(|(_, entry)| entry.proposed)
503                .map(|(_, entry)| entry.name.as_str())
504                .collect();
505            if names.is_empty() {
506                continue;
507            }
508            text.push_str(&format!("\n{title}\n"));
509            for name in names {
510                text.push_str(&format!("  {name}\n"));
511            }
512        }
513        text
514    }
515}
516
517/// How far a scan is, for the lines of the scanning view.
518#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
519pub struct ScanCounts {
520    /// Classes of the module that other modules use, and in how many files.
521    pub used_classes: usize,
522    pub used_files: usize,
523    pub contracts: usize,
524    pub events: usize,
525    pub commands: usize,
526}
527
528/// A class the module declares, as the scan needs it.
529struct Found {
530    class: String,
531    interface: bool,
532    /// The kind of the folder its file is in.
533    folder: String,
534    command: Option<String>,
535}
536
537/// A scan in progress. It reads the files of one module, a few at each step, so
538/// that the interface can show how far it is and stop it.
539pub struct SurfaceScan {
540    module: String,
541    kinds: Kinds,
542    /// The module's PHP files outside its tests: the path, and the path inside the module.
543    files: Vec<(PathBuf, String)>,
544    next: usize,
545    found: Vec<Found>,
546    /// Each class of the module that another module uses, with the files that use
547    /// it by the module they are in.
548    used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
549}
550
551impl SurfaceScan {
552    /// Starts a scan of one module of the app. `None` when the app has no such module.
553    pub fn start(app: &AppSnapshot, module: &str) -> Option<Self> {
554        let found = app.module(module)?;
555        let (layout, config) = Layout::read(&app.root);
556        let kinds = Kinds::new(config.as_ref(), &layout.app_folder);
557        let files = files_of(&found.dir)
558            .into_iter()
559            .filter(|(_, relative)| is_php(relative) && kinds.of(relative) != TESTS)
560            .collect();
561
562        // Classes that other modules use: the links Mortise already has.
563        let mut used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>> = BTreeMap::new();
564        for link in app.links.iter().filter(|link| link.to == module) {
565            for reference in &link.refs {
566                used.entry(reference.class.clone())
567                    .or_default()
568                    .entry(link.from.clone())
569                    .or_default()
570                    .insert(reference.file.clone());
571            }
572        }
573        Some(Self {
574            module: module.to_owned(),
575            kinds,
576            files,
577            next: 0,
578            found: Vec::new(),
579            used,
580        })
581    }
582
583    /// How many files the scan reads in all.
584    pub fn total(&self) -> usize {
585        self.files.len()
586    }
587
588    /// How many files are read.
589    pub fn read(&self) -> usize {
590        self.next
591    }
592
593    pub fn module(&self) -> &str {
594        &self.module
595    }
596
597    /// Reads up to `files` more files. Returns true when every file is read.
598    pub fn step(&mut self, files: usize) -> bool {
599        let end = (self.next + files).min(self.files.len());
600        for (path, relative) in &self.files[self.next..end] {
601            let folder = self.kinds.of(relative);
602            let analysis = analyze(&std::fs::read(path).unwrap_or_default());
603            for declared in analysis.declares {
604                self.found.push(Found {
605                    command: command_of(&declared, &folder),
606                    class: declared.class,
607                    interface: declared.kind == DeclaredKind::Interface,
608                    folder: folder.clone(),
609                });
610            }
611        }
612        self.next = end;
613        self.next == self.files.len()
614    }
615
616    /// What was found so far.
617    pub fn counts(&self) -> ScanCounts {
618        let files: BTreeSet<&String> = self
619            .used
620            .values()
621            .flat_map(|users| users.values().flatten())
622            .collect();
623        ScanCounts {
624            used_classes: self.used.len(),
625            used_files: files.len(),
626            contracts: self.found.iter().filter(|found| found.interface).count(),
627            events: self.found.iter().filter(|found| is_event(found)).count(),
628            commands: self
629                .found
630                .iter()
631                .filter(|found| found.command.is_some())
632                .count(),
633        }
634    }
635
636    /// Makes the proposal from what was read.
637    ///
638    /// `routes` are the URIs of the module's routes, when a running app gave them.
639    /// `scheduled` are the scheduled tasks of the app: a target and its schedule.
640    pub fn finish(self, routes: Option<&[String]>, scheduled: &[(String, String)]) -> Proposal {
641        let users = |class: &str| -> Vec<(String, usize)> {
642            let mut users: Vec<(String, usize)> = self
643                .used
644                .get(class)
645                .map(|users| {
646                    users
647                        .iter()
648                        .map(|(module, files)| (module.clone(), files.len()))
649                        .collect()
650                })
651                .unwrap_or_default();
652            users.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
653            users
654        };
655        let class_entry = |kind: SurfaceKind, found: &Found| {
656            let mut entry = SurfaceEntry::new(kind, found.class.clone());
657            entry.folder = found.folder.clone();
658            entry.used_by = users(&found.class);
659            entry
660        };
661        // What is used from outside first, then by name.
662        let sorted = |mut entries: Vec<SurfaceEntry>| {
663            entries.sort_by(|a, b| {
664                b.used_files()
665                    .cmp(&a.used_files())
666                    .then_with(|| a.name.cmp(&b.name))
667            });
668            entries
669        };
670
671        let contracts: Vec<SurfaceEntry> = self
672            .found
673            .iter()
674            .filter(|found| found.interface)
675            .map(|found| class_entry(SurfaceKind::Contract, found))
676            .collect();
677        let events: Vec<SurfaceEntry> = self
678            .found
679            .iter()
680            .filter(|found| is_event(found))
681            .map(|found| class_entry(SurfaceKind::Event, found))
682            .collect();
683        // A class another module uses that is neither: shown, and not proposed.
684        let listed: BTreeSet<&str> = contracts
685            .iter()
686            .chain(&events)
687            .map(|entry| entry.name.as_str())
688            .collect();
689        let others: Vec<SurfaceEntry> = self
690            .used
691            .keys()
692            .filter(|class| !listed.contains(class.as_str()))
693            .map(|class| {
694                let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, class.clone());
695                entry.folder = self
696                    .found
697                    .iter()
698                    .find(|found| &found.class == class)
699                    .map(|found| found.folder.clone())
700                    .unwrap_or_default();
701                entry.used_by = users(class);
702                entry.proposed = false;
703                entry
704            })
705            .collect();
706
707        // The routes of the module, by their prefix.
708        let mut patterns: BTreeMap<String, usize> = BTreeMap::new();
709        for uri in routes.unwrap_or_default() {
710            *patterns.entry(pattern_of(uri)).or_default() += 1;
711        }
712        let mut route_entries: Vec<SurfaceEntry> = patterns
713            .into_iter()
714            .map(|(pattern, count)| {
715                let mut entry = SurfaceEntry::new(SurfaceKind::Route, pattern);
716                entry.routes = count;
717                entry
718            })
719            .collect();
720        route_entries.sort_by(|a, b| b.routes.cmp(&a.routes).then_with(|| a.name.cmp(&b.name)));
721
722        let mut commands: Vec<SurfaceEntry> = self
723            .found
724            .iter()
725            .filter_map(|found| found.command.as_ref())
726            .map(|name| {
727                let mut entry = SurfaceEntry::new(SurfaceKind::Command, name.clone());
728                // A scheduled task runs the command when its target is `php artisan <name>`.
729                entry.schedule = scheduled
730                    .iter()
731                    .find(|(target, _)| artisan_command(target) == Some(name.as_str()))
732                    .map(|(_, schedule)| schedule.clone());
733                entry
734            })
735            .collect();
736        commands.sort_by(|a, b| {
737            b.schedule
738                .is_some()
739                .cmp(&a.schedule.is_some())
740                .then_with(|| a.name.cmp(&b.name))
741        });
742
743        let mut entries = sorted(contracts);
744        entries.extend(sorted(events));
745        entries.extend(sorted(others));
746        entries.extend(route_entries);
747        entries.extend(commands);
748        Proposal {
749            module: self.module,
750            entries,
751            routes_read: routes.is_some(),
752            declared: self
753                .found
754                .iter()
755                .map(|found| (found.class.clone(), found.folder.clone()))
756                .collect(),
757            commands: self
758                .found
759                .iter()
760                .filter_map(|found| found.command.clone())
761                .collect(),
762            uris: routes.unwrap_or_default().to_vec(),
763        }
764    }
765}
766
767/// True when two class names are the same class: PHP ignores case and a leading backslash.
768fn same_class(a: &str, b: &str) -> bool {
769    a.trim_start_matches('\\')
770        .eq_ignore_ascii_case(b.trim_start_matches('\\'))
771}
772
773/// True for a full class name as the package stores it: parts of letters, digits and
774/// `_` joined by a backslash, no part starting with a digit, no leading backslash.
775fn is_class_name(class: &str) -> bool {
776    class.split('\\').all(|part| {
777        let mut bytes = part.bytes();
778        let word = |byte: u8| byte == b'_' || byte >= 0x80 || byte.is_ascii_alphanumeric();
779        bytes
780            .next()
781            .is_some_and(|first| word(first) && !first.is_ascii_digit())
782            && bytes.all(word)
783    })
784}
785
786/// True for a command name as the package stores it: parts without white space joined by `:`.
787fn is_command_name(command: &str) -> bool {
788    command
789        .split(':')
790        .all(|part| !part.is_empty() && !part.chars().any(char::is_whitespace))
791}
792
793/// A route as the package stores it: without `/` at its ends, and `/` for the root.
794/// `None` for a route the package refuses: empty, or with white space.
795fn stored_route(route: &str) -> Option<String> {
796    if route.is_empty() || route.chars().any(char::is_whitespace) {
797        return None;
798    }
799    let route = route.trim_matches('/');
800    Some(if route.is_empty() { "/" } else { route }.to_owned())
801}
802
803fn is_event(found: &Found) -> bool {
804    !found.interface && found.folder == EVENTS
805}
806
807/// The pattern a route is proposed under: its first part and everything below it,
808/// or its first two parts for an API route. `api/billing/invoices/{invoice}` is
809/// under `api/billing/*`.
810fn pattern_of(uri: &str) -> String {
811    if uri.trim_matches('/').is_empty() {
812        return "/".to_owned();
813    }
814    let parts: Vec<&str> = uri.trim_matches('/').split('/').collect();
815    let take = if parts.first() == Some(&"api") { 2 } else { 1 };
816    let prefix: Vec<&str> = parts
817        .iter()
818        .copied()
819        .take(take)
820        .take_while(|part| !part.is_empty() && !part.starts_with('{'))
821        .collect();
822    if prefix.len() < take || prefix.is_empty() {
823        // Nothing fixed to group by: the route stands for itself.
824        return uri.trim_matches('/').to_owned();
825    }
826    format!("{}/*", prefix.join("/"))
827}
828
829/// True when a route is under a pattern: the pattern itself, or with `/*` at its
830/// end, the prefix and everything below it.
831fn pattern_matches(pattern: &str, uri: &str) -> bool {
832    let (pattern, uri) = (pattern.trim_matches('/'), uri.trim_matches('/'));
833    match pattern.strip_suffix("/*") {
834        Some(prefix) => {
835            uri == prefix
836                || uri
837                    .strip_prefix(prefix)
838                    .is_some_and(|rest| rest.starts_with('/'))
839        }
840        None => pattern == uri,
841    }
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847
848    #[test]
849    fn a_route_is_proposed_under_its_prefix() {
850        assert_eq!(
851            pattern_of("api/billing/invoices/{invoice}"),
852            "api/billing/*"
853        );
854        assert_eq!(pattern_of("billing/invoices"), "billing/*");
855        assert_eq!(pattern_of("checkout"), "checkout/*");
856        assert_eq!(pattern_of("/api/billing"), "api/billing/*");
857        // Nothing fixed to group by.
858        assert_eq!(pattern_of("{tenant}/invoices"), "{tenant}/invoices");
859        assert_eq!(
860            pattern_of("api/{version}/invoices"),
861            "api/{version}/invoices"
862        );
863        assert_eq!(pattern_of("api"), "api");
864        // The root route stays the root, which the package stores as `/`.
865        assert_eq!(pattern_of("/"), "/");
866        assert_eq!(pattern_of(""), "/");
867        assert!(pattern_matches("/", "/"));
868
869        assert!(pattern_matches("billing/*", "billing"));
870        assert!(pattern_matches("billing/*", "billing/invoices/{invoice}"));
871        assert!(!pattern_matches("billing/*", "billings/list"));
872        assert!(pattern_matches("checkout/confirm", "checkout/confirm"));
873        assert!(!pattern_matches("checkout/confirm", "checkout/confirm/now"));
874    }
875}