Skip to main content

mortise_core/modules/
layout.rs

1//! Where the package keeps things in an app: read from `config/modules.php` without running PHP.
2
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::php::{ConfigValue, Lookup, read_config};
8
9/// A setting of `config/modules.php` that Mortise needs.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11pub enum LayoutKey {
12    /// `namespace`
13    Namespace,
14    /// `paths.modules`
15    ModulesFolder,
16    /// `paths.app_folder`
17    AppFolder,
18    /// `activators.file.statuses-file`
19    StatusesFile,
20    /// `activator`
21    Activator,
22}
23
24impl LayoutKey {
25    /// The key as it is written in `config/modules.php`.
26    pub fn config_key(self) -> &'static str {
27        match self {
28            LayoutKey::Namespace => "namespace",
29            LayoutKey::ModulesFolder => "paths.modules",
30            LayoutKey::AppFolder => "paths.app_folder",
31            LayoutKey::StatusesFile => "activators.file.statuses-file",
32            LayoutKey::Activator => "activator",
33        }
34    }
35}
36
37/// Where the modules of an app live and how their state is kept.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Layout {
40    /// The folder that holds one folder per module. Absolute.
41    pub modules_dir: PathBuf,
42    /// The namespace all modules share, `Modules` by default.
43    pub namespace: String,
44    /// The folder inside a module that holds its classes, `app/` since version 11 of the package.
45    pub app_folder: String,
46    /// The file that records which modules are on. Absolute.
47    pub statuses_file: PathBuf,
48    /// The activator the app uses. Only `file` keeps the state in `statuses_file`.
49    pub activator: String,
50    /// True when the app has a `config/modules.php`.
51    pub has_config: bool,
52    /// Settings that are in the config file but need PHP to evaluate.
53    /// The package default is used for each, which can be wrong.
54    pub assumed: Vec<LayoutKey>,
55}
56
57/// Reads the layout of the app in `root` from `config/modules.php` now, without
58/// the rest of the app. A confirmation checks it again just before a delete.
59pub fn read_layout(root: &Path) -> Layout {
60    Layout::read(root).0
61}
62
63impl Layout {
64    /// Reads the layout of the app in `root`, and gives the config it came from.
65    /// A missing config file means the package defaults.
66    pub(crate) fn read(root: &Path) -> (Self, Option<ConfigValue>) {
67        let mut layout = Self {
68            modules_dir: root.join("Modules"),
69            namespace: "Modules".into(),
70            app_folder: "app/".into(),
71            statuses_file: root.join("modules_statuses.json"),
72            activator: "file".into(),
73            has_config: false,
74            assumed: Vec::new(),
75        };
76
77        let Ok(source) = std::fs::read(root.join("config").join("modules.php")) else {
78            return (layout, None);
79        };
80        layout.has_config = true;
81
82        let Some(config) = read_config(&source) else {
83            // The file does not return an array at its top level, so nothing in it can be trusted.
84            layout.assumed = vec![
85                LayoutKey::Namespace,
86                LayoutKey::ModulesFolder,
87                LayoutKey::AppFolder,
88                LayoutKey::StatusesFile,
89                LayoutKey::Activator,
90            ];
91            return (layout, None);
92        };
93
94        // A top-level key of the app's file replaces the package's whole value for that key,
95        // so a missing nested key is not the default at run time. Mortise still uses the
96        // default here: it is what the package's own fallbacks do for the modules folder,
97        // and for the rest there is nothing better to show.
98        let mut text =
99            |path: &[&str], key: LayoutKey, target: &mut String| match config.lookup(path) {
100                Lookup::Found(ConfigValue::Str(value)) => *target = value.clone(),
101                Lookup::Found(_) | Lookup::Unresolved => layout.assumed.push(key),
102                Lookup::Missing => {}
103            };
104        text(&["namespace"], LayoutKey::Namespace, &mut layout.namespace);
105        text(
106            &["paths", "app_folder"],
107            LayoutKey::AppFolder,
108            &mut layout.app_folder,
109        );
110        text(&["activator"], LayoutKey::Activator, &mut layout.activator);
111
112        let mut path =
113            |path: &[&str], key: LayoutKey, target: &mut PathBuf| match config.lookup(path) {
114                Lookup::Found(ConfigValue::BasePath(relative)) => *target = root.join(relative),
115                // A plain string is a path as PHP would see it: absolute, or relative to
116                // wherever PHP runs. Only the absolute form can be followed from here.
117                Lookup::Found(ConfigValue::Str(value)) if Path::new(value).is_absolute() => {
118                    *target = PathBuf::from(value);
119                }
120                Lookup::Found(_) | Lookup::Unresolved => layout.assumed.push(key),
121                Lookup::Missing => {}
122            };
123        path(
124            &["paths", "modules"],
125            LayoutKey::ModulesFolder,
126            &mut layout.modules_dir,
127        );
128        path(
129            &["activators", "file", "statuses-file"],
130            LayoutKey::StatusesFile,
131            &mut layout.statuses_file,
132        );
133
134        (layout, Some(config))
135    }
136
137    /// True when the on or off state of modules is in the statuses file.
138    pub fn uses_file_activator(&self) -> bool {
139        self.activator == "file"
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn app_with_config(config: Option<&str>) -> tempfile::TempDir {
148        let dir = tempfile::tempdir().unwrap();
149        if let Some(config) = config {
150            std::fs::create_dir(dir.path().join("config")).unwrap();
151            std::fs::write(dir.path().join("config/modules.php"), config).unwrap();
152        }
153        dir
154    }
155
156    #[test]
157    fn no_config_file_means_the_package_defaults() {
158        let app = app_with_config(None);
159        let (layout, _) = Layout::read(app.path());
160        assert_eq!(layout.modules_dir, app.path().join("Modules"));
161        assert_eq!(layout.namespace, "Modules");
162        assert_eq!(layout.app_folder, "app/");
163        assert_eq!(
164            layout.statuses_file,
165            app.path().join("modules_statuses.json")
166        );
167        assert!(layout.uses_file_activator());
168        assert!(!layout.has_config);
169        assert!(layout.assumed.is_empty());
170    }
171
172    #[test]
173    fn reads_what_the_app_changed() {
174        let app = app_with_config(Some(
175            r#"<?php return [
176                'namespace' => 'Acme',
177                'paths' => ['modules' => base_path('src/Domains'), 'app_folder' => 'src/'],
178                'activators' => ['file' => ['statuses-file' => base_path('storage/modules.json')]],
179                'activator' => 'database',
180            ];"#,
181        ));
182        let (layout, _) = Layout::read(app.path());
183        assert_eq!(layout.modules_dir, app.path().join("src/Domains"));
184        assert_eq!(layout.namespace, "Acme");
185        assert_eq!(layout.app_folder, "src/");
186        assert_eq!(
187            layout.statuses_file,
188            app.path().join("storage/modules.json")
189        );
190        assert!(!layout.uses_file_activator());
191        assert!(layout.has_config);
192        assert!(layout.assumed.is_empty());
193    }
194
195    #[test]
196    fn what_needs_php_is_assumed_and_named() {
197        let app = app_with_config(Some(
198            r#"<?php return [
199                'namespace' => env('MODULES_NAMESPACE', 'Modules'),
200                'paths' => ['modules' => __DIR__ . '/../Modules', 'app_folder' => 'app/'],
201            ];"#,
202        ));
203        let (layout, _) = Layout::read(app.path());
204        assert_eq!(layout.namespace, "Modules");
205        assert_eq!(layout.modules_dir, app.path().join("Modules"));
206        assert_eq!(
207            layout.assumed,
208            vec![LayoutKey::Namespace, LayoutKey::ModulesFolder]
209        );
210    }
211
212    #[test]
213    fn a_relative_string_path_cannot_be_followed() {
214        let app = app_with_config(Some("<?php return ['paths' => ['modules' => 'Modules']];"));
215        let (layout, _) = Layout::read(app.path());
216        assert_eq!(layout.modules_dir, app.path().join("Modules"));
217        assert_eq!(layout.assumed, vec![LayoutKey::ModulesFolder]);
218
219        // A part of the path that only PHP knows: the modules folder could be anywhere.
220        for config in [
221            "<?php return ['paths' => $paths];",
222            "<?php return ['paths' => [...$paths]];",
223        ] {
224            let app = app_with_config(Some(config));
225            let (layout, _) = Layout::read(app.path());
226            assert!(
227                layout.assumed.contains(&LayoutKey::ModulesFolder),
228                "{config}"
229            );
230        }
231    }
232
233    #[test]
234    fn a_config_file_that_returns_nothing_assumes_everything() {
235        let app = app_with_config(Some("<?php $config = [];"));
236        let (layout, _) = Layout::read(app.path());
237        assert!(layout.has_config);
238        assert_eq!(layout.assumed.len(), 5);
239    }
240}