mago-guard 1.30.0

A PHP dependencies guard that helps keep your architecture clean.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::fmt;

use foldhash::HashMap;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde::de;
use serde::de::Deserializer;
use serde::de::MapAccess;
use serde::de::Visitor;
use serde::ser::SerializeStruct;
use serde::ser::Serializer;

use crate::path::NamespacePath;
use crate::path::Path;
use crate::path::is_valid_identifier_part;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct Settings {
    pub mode: GuardMode,
    pub perimeter: PerimeterSettings,
    pub structural: StructuralSettings,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct PerimeterSettings {
    pub layers: HashMap<String, Vec<Path>>,
    pub layering: Vec<NamespacePath>,
    pub rules: Vec<PerimeterRule>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PerimeterRule {
    pub namespace: NamespacePath,
    pub permit: Vec<PermittedDependency>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, JsonSchema)]
#[schemars(untagged)]
pub enum PermittedDependency {
    Dependency(Path),
    DependencyOfKind { path: Path, kinds: Vec<PermittedDependencyKind> },
}

/// Represents the specific types of symbols allowed from a path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum PermittedDependencyKind {
    ClassLike,
    Function,
    Constant,
    Attribute,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct StructuralSettings {
    /// A list of structural rules to enforce across the codebase.
    pub rules: Vec<StructuralRule>,
}

/// Represents a single structural enforcement rule from `[[guard.structural.rules]]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct StructuralRule {
    /// The namespace pattern this rule applies to.
    pub on: String,
    /// An optional exclusion pattern; if the namespace matches this, the rule is skipped.
    pub not_on: Option<String>,
    /// The kind of symbol this policy applies to (e.g., "class").
    pub target: Option<StructuralSymbolKind>,
    /// Restricts the namespace to only contain the specified symbol kinds.
    pub must_be: Option<Vec<StructuralSymbolKind>>,
    /// Optional naming pattern the symbol's name must match.
    pub must_be_named: Option<String>,
    /// If true, the symbol must be declared `final`.
    pub must_be_final: Option<bool>,
    /// If true, the symbol must be declared `abstract`.
    pub must_be_abstract: Option<bool>,
    /// If true, the symbol must be declared `readonly`.
    pub must_be_readonly: Option<bool>,
    /// Structural implementation constraints.
    pub must_implement: Option<StructuralInheritanceConstraint>,
    /// Structural extension constraints.
    pub must_extend: Option<StructuralInheritanceConstraint>,
    /// Structural trait usage constraints.
    pub must_use_trait: Option<StructuralInheritanceConstraint>,
    /// Structural attribute usage constraints.
    pub must_use_attribute: Option<StructuralInheritanceConstraint>,
    /// A human-readable reason for this rule.
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum StructuralSymbolKind {
    ClassLike,
    Class,
    Interface,
    Trait,
    Enum,
    Constant,
    Function,
}

/// Represents a logical constraint for `implement`, `extend`, or `use_traits`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
#[serde(untagged)]
#[schemars(untagged)]
pub enum StructuralInheritanceConstraint {
    /// An OR of ANDs, e.g., `[["A", "B"], ["C"]]`
    AnyOfAllOf(Vec<Vec<String>>),
    /// An AND group, e.g., `["A", "B"]`
    AllOf(Vec<String>),
    /// A single required item, e.g., `"A"`
    Single(String),
    /// `None` indicates the rule requires no constraints.
    Nothing,
}

impl PermittedDependencyKind {
    /// Returns the string representation of the symbol type.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            PermittedDependencyKind::ClassLike => "class-like",
            PermittedDependencyKind::Function => "function",
            PermittedDependencyKind::Constant => "constant",
            PermittedDependencyKind::Attribute => "attribute",
        }
    }
}

impl StructuralSymbolKind {
    #[must_use]
    pub const fn is_constant(&self) -> bool {
        matches!(self, StructuralSymbolKind::Constant)
    }

    /// Returns the string representation of the symbol kind.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            StructuralSymbolKind::ClassLike => "class-like",
            StructuralSymbolKind::Class => "class",
            StructuralSymbolKind::Interface => "interface",
            StructuralSymbolKind::Trait => "trait",
            StructuralSymbolKind::Enum => "enum",
            StructuralSymbolKind::Constant => "constant",
            StructuralSymbolKind::Function => "function",
        }
    }
}

impl<'de> Deserialize<'de> for PermittedDependency {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct AllowedPathVisitor;

        impl<'de> Visitor<'de> for AllowedPathVisitor {
            type Value = PermittedDependency;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a path string or a detailed object with path and types")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let path = Path::deserialize(de::value::StrDeserializer::new(value))?;
                Ok(PermittedDependency::Dependency(path))
            }

            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                #[derive(Deserialize)]
                struct DetailedHelper {
                    path: Path,
                    kinds: Vec<PermittedDependencyKind>,
                }

                let helper: DetailedHelper = Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))?;

                Ok(PermittedDependency::DependencyOfKind { path: helper.path, kinds: helper.kinds })
            }
        }

        deserializer.deserialize_any(AllowedPathVisitor)
    }
}

impl<'de> Deserialize<'de> for StructuralInheritanceConstraint {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // Helper enum to let serde handle the shape detection (string vs array vs array of arrays).
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Untagged {
            AnyOfAllOf(Vec<Vec<String>>),
            AllOf(Vec<String>),
            Single(String),
        }

        match Untagged::deserialize(deserializer)? {
            Untagged::Single(s) => {
                if s.eq_ignore_ascii_case("@nothing") {
                    Ok(Self::Nothing)
                } else if s.split('\\').all(is_valid_identifier_part) {
                    Ok(Self::Single(s))
                } else {
                    Err(de::Error::custom(format!("Expected a valid fully qualified name or '@nothing', found '{s}'")))
                }
            }
            Untagged::AllOf(items) => {
                for item in &items {
                    if !item.split('\\').all(is_valid_identifier_part) {
                        return Err(de::Error::custom(format!("'{item}' is not a valid fully qualified name")));
                    }
                }

                Ok(Self::AllOf(items))
            }
            Untagged::AnyOfAllOf(groups) => {
                for group in &groups {
                    for item in group {
                        if !item.split('\\').all(is_valid_identifier_part) {
                            return Err(de::Error::custom(format!("'{item}' is not a valid fully qualified name")));
                        }
                    }
                }

                Ok(Self::AnyOfAllOf(groups))
            }
        }
    }
}

impl Serialize for PermittedDependency {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            PermittedDependency::Dependency(path) => path.serialize(serializer),
            PermittedDependency::DependencyOfKind { path, kinds } => {
                let mut state = serializer.serialize_struct("DependencyOfKind", 2)?;
                state.serialize_field("path", path)?;
                state.serialize_field("kinds", kinds)?;
                state.end()
            }
        }
    }
}

impl fmt::Display for PermittedDependencyKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl fmt::Display for StructuralInheritanceConstraint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            // "nothing"
            Self::Nothing => write!(f, "<nothing>"),
            // "`SomeInterface`"
            Self::Single(item) => write!(f, "`{item}`"),
            // "`InterfaceA` and `InterfaceB`"
            Self::AllOf(items) => {
                let formatted = items.iter().map(|item| format!("`{item}`")).collect::<Vec<_>>().join(" and ");
                write!(f, "{formatted}")
            }
            // "(`InterfaceA` and `InterfaceB`) or `InterfaceC`"
            Self::AnyOfAllOf(groups) => {
                let formatted = groups
                    .iter()
                    .map(|group| {
                        let inner = group.iter().map(|item| format!("`{item}`")).collect::<Vec<_>>().join(" and ");
                        if group.len() > 1 { format!("({inner})") } else { inner }
                    })
                    .collect::<Vec<_>>()
                    .join(" or ");
                write!(f, "{formatted}")
            }
        }
    }
}

impl fmt::Display for StructuralSymbolKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl PerimeterSettings {
    /// Returns true if there are no perimeter rules or layering configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty() && self.layering.is_empty()
    }
}

impl StructuralSettings {
    /// Returns true if there are no structural rules configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }
}

impl Settings {
    /// Returns true if perimeter guard has configuration.
    #[must_use]
    pub fn has_perimeter_config(&self) -> bool {
        !self.perimeter.is_empty()
    }

    /// Returns true if structural guard has configuration.
    #[must_use]
    pub fn has_structural_config(&self) -> bool {
        !self.structural.is_empty()
    }

    /// Returns whether structural guard should run.
    ///
    /// - `None` - mode does not allow structural guard
    /// - `Some(true)` - should run, configuration exists
    /// - `Some(false)` - should run but no configuration
    #[must_use]
    pub fn should_run_structural(&self) -> Option<bool> {
        if !self.mode.includes_structural() {
            return None;
        }

        Some(self.has_structural_config())
    }

    /// Returns whether perimeter guard should run.
    ///
    /// - `None` - mode does not allow perimeter guard
    /// - `Some(true)` - should run, configuration exists
    /// - `Some(false)` - should run but no configuration
    #[must_use]
    pub fn should_run_perimeter(&self) -> Option<bool> {
        if !self.mode.includes_perimeter() {
            return None;
        }

        Some(self.has_perimeter_config())
    }
}

/// Specifies which guard modes to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum GuardMode {
    /// Run both structural and perimeter guards (default)
    #[default]
    Default,
    /// Run only structural guard
    Structural,
    /// Run only perimeter guard
    Perimeter,
}

impl GuardMode {
    /// Returns true if the mode includes structural guard.
    #[must_use]
    pub const fn includes_structural(&self) -> bool {
        matches!(self, GuardMode::Default | GuardMode::Structural)
    }

    /// Returns true if the mode includes perimeter guard.
    #[must_use]
    pub const fn includes_perimeter(&self) -> bool {
        matches!(self, GuardMode::Default | GuardMode::Perimeter)
    }

    /// Returns the string representation of the guard mode.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            GuardMode::Default => "default",
            GuardMode::Structural => "structural",
            GuardMode::Perimeter => "perimeter",
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn test_structural_inheritance_constraint_display() {
        let single = StructuralInheritanceConstraint::Single("SomeInterface".to_string());
        assert_eq!(single.to_string(), "`SomeInterface`");

        let all_of = StructuralInheritanceConstraint::AllOf(vec!["InterfaceA".to_string(), "InterfaceB".to_string()]);
        assert_eq!(all_of.to_string(), "`InterfaceA` and `InterfaceB`");

        let any_of_all_of = StructuralInheritanceConstraint::AnyOfAllOf(vec![
            vec!["InterfaceA".to_string(), "InterfaceB".to_string()],
            vec!["InterfaceC".to_string()],
        ]);
        assert_eq!(any_of_all_of.to_string(), "(`InterfaceA` and `InterfaceB`) or `InterfaceC`");

        let none = StructuralInheritanceConstraint::Nothing;
        assert_eq!(none.to_string(), "<nothing>");
    }

    #[derive(Deserialize)]
    struct Wrapper {
        constraint: StructuralInheritanceConstraint,
    }

    #[test]
    fn it_deserializes_none_keyword() {
        let toml = r#"constraint = "@nothing""#;
        let wrapped: Wrapper = toml::from_str(toml).unwrap();
        assert_eq!(wrapped.constraint, StructuralInheritanceConstraint::Nothing);
    }

    #[test]
    fn it_deserializes_valid_single_string() {
        let toml = r#"constraint = "App\\Domain\\MyInterface""#;
        let wrapped: Wrapper = toml::from_str(toml).unwrap();
        assert_eq!(wrapped.constraint, StructuralInheritanceConstraint::Single("App\\Domain\\MyInterface".to_string()));
    }

    #[test]
    fn it_deserializes_valid_array_of_strings() {
        let toml = r#"constraint = ["App\\InterfaceA", "App\\InterfaceB"]"#;
        let wrapped: Wrapper = toml::from_str(toml).unwrap();
        assert_eq!(
            wrapped.constraint,
            StructuralInheritanceConstraint::AllOf(vec!["App\\InterfaceA".to_string(), "App\\InterfaceB".to_string()])
        );
    }

    #[test]
    fn it_deserializes_valid_array_of_arrays() {
        let toml = r#"constraint = [["App\\A", "App\\B"], ["App\\C"]]"#;
        let wrapped: Wrapper = toml::from_str(toml).unwrap();
        assert_eq!(
            wrapped.constraint,
            StructuralInheritanceConstraint::AnyOfAllOf(vec![
                vec!["App\\A".to_string(), "App\\B".to_string()],
                vec!["App\\C".to_string()]
            ])
        );
    }

    #[test]
    fn it_fails_on_invalid_identifier_in_single_string() {
        let toml = r#"constraint = "Invalid-Interface""#;
        assert!(toml::from_str::<Wrapper>(toml).is_err());
    }

    #[test]
    fn it_fails_on_invalid_identifier_in_array() {
        let toml = r#"constraint = ["App\\InterfaceA", "Invalid-Interface"]"#;
        assert!(toml::from_str::<Wrapper>(toml).is_err());
    }

    #[test]
    fn it_fails_on_invalid_identifier_in_nested_array() {
        let toml = r#"constraint = [["App\\A", "Invalid-B"], ["App\\C"]]"#;
        assert!(toml::from_str::<Wrapper>(toml).is_err());
    }
}