1use 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
20const EVENTS: &str = "Events";
22
23#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct AcceptedSurface {
31 #[serde(default)]
33 pub classes: Vec<String>,
34 #[serde(default)]
36 pub routes: Vec<String>,
37 #[serde(default)]
39 pub commands: Vec<String>,
40}
41
42impl AcceptedSurface {
43 pub(crate) fn of_manifest(manifest: &serde_json::Value) -> Option<Self> {
48 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 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 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 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 pub fn entries(&self) -> usize {
106 self.classes.len() + self.routes.len() + self.commands.len()
107 }
108
109 pub fn has_class(&self, class: &str) -> bool {
111 self.classes.iter().any(|listed| same_class(listed, class))
112 }
113
114 fn covers(&self, uri: &str) -> bool {
116 self.routes.iter().any(|route| pattern_matches(route, uri))
117 }
118
119 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 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 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 pub fn to_stdin(&self) -> String {
157 serde_json::to_string(self).expect("a surface is plain data")
158 }
159}
160
161pub 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
171pub struct SurfaceAnswer {
172 pub module: String,
173 #[serde(default)]
175 pub surface: Option<AcceptedSurface>,
176 #[serde(default)]
178 pub changed: bool,
179 #[serde(default)]
180 pub errors: Vec<SurfaceProblem>,
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
185pub struct SurfaceProblem {
186 pub message: String,
187}
188
189#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct Difference {
192 pub entry: SurfaceEntry,
194 pub new: bool,
197 pub taken: bool,
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
203pub enum SurfaceKind {
204 Contract,
206 Event,
208 OtherClass,
210 Route,
212 Command,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct SurfaceEntry {
219 pub kind: SurfaceKind,
220 pub name: String,
222 pub folder: String,
224 pub used_by: Vec<(String, usize)>,
226 pub routes: usize,
228 pub schedule: Option<String>,
230 pub proposed: bool,
232 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 pub fn used_files(&self) -> usize {
252 self.used_by.iter().map(|(_, files)| files).sum()
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
258pub enum Typed {
259 Class { folder: String },
261 Command,
263 Route { routes: usize },
265 Listed,
267 Unknown,
269}
270
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273pub struct Proposal {
274 pub module: String,
275 pub entries: Vec<SurfaceEntry>,
278 pub routes_read: bool,
280 declared: BTreeMap<String, String>,
282 commands: BTreeSet<String>,
284 uris: Vec<String>,
286}
287
288impl Proposal {
289 pub fn found(&self) -> usize {
291 self.entries.len()
292 }
293
294 pub fn proposed(&self) -> usize {
296 self.entries.iter().filter(|entry| entry.proposed).count()
297 }
298
299 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 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 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 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 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
519pub struct ScanCounts {
520 pub used_classes: usize,
522 pub used_files: usize,
523 pub contracts: usize,
524 pub events: usize,
525 pub commands: usize,
526}
527
528struct Found {
530 class: String,
531 interface: bool,
532 folder: String,
534 command: Option<String>,
535}
536
537pub struct SurfaceScan {
540 module: String,
541 kinds: Kinds,
542 files: Vec<(PathBuf, String)>,
544 next: usize,
545 found: Vec<Found>,
546 used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
549}
550
551impl SurfaceScan {
552 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 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 pub fn total(&self) -> usize {
585 self.files.len()
586 }
587
588 pub fn read(&self) -> usize {
590 self.next
591 }
592
593 pub fn module(&self) -> &str {
594 &self.module
595 }
596
597 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 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 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 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 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 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 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
767fn same_class(a: &str, b: &str) -> bool {
769 a.trim_start_matches('\\')
770 .eq_ignore_ascii_case(b.trim_start_matches('\\'))
771}
772
773fn 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
786fn is_command_name(command: &str) -> bool {
788 command
789 .split(':')
790 .all(|part| !part.is_empty() && !part.chars().any(char::is_whitespace))
791}
792
793fn 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
807fn 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 return uri.trim_matches('/').to_owned();
825 }
826 format!("{}/*", prefix.join("/"))
827}
828
829fn 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 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 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}