mago-guard 1.2.2

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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use std::borrow::Cow;
use std::sync::LazyLock;

use ahash::HashSet;
use bumpalo::Bump;
use indoc::indoc;

use mago_atom::AtomSet;
use mago_codex::populator::populate_codebase;
use mago_codex::scanner::scan_program;
use mago_database::DatabaseReader;
use mago_database::file::File;
use mago_guard::ArchitecturalGuard;
use mago_guard::path::NamespacePath;
use mago_guard::path::Path;
use mago_guard::path::SymbolSelector;
use mago_guard::report::FortressReport;
use mago_guard::report::breach::BreachVector;
use mago_guard::settings::PerimeterRule;
use mago_guard::settings::PerimeterSettings;
use mago_guard::settings::PermittedDependency;
use mago_guard::settings::PermittedDependencyKind;
use mago_guard::settings::Settings;
use mago_names::resolver::NameResolver;
use mago_prelude::Prelude;
use mago_syntax::parser::parse_file;

static PRELUDE: LazyLock<Prelude> = LazyLock::new(Prelude::build);

/// Creates settings with a deny-all rule for the App\Module\ namespace.
/// This is needed because the guard now skips when there's no perimeter config.
fn deny_all_settings() -> Settings {
    Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![], // Deny everything
            }],
            ..Default::default()
        },
        ..Default::default()
    }
}

fn test_guard(name: &'static str, code: &'static str, settings: Settings) -> FortressReport {
    let Prelude { mut database, mut metadata, mut symbol_references } = PRELUDE.clone();

    let file = File::ephemeral(Cow::Borrowed(name), Cow::Borrowed(code));
    let file_id = database.add(file);
    let source_file = database.get_ref(&file_id).expect("File just added should exist");

    let arena = Bump::new();
    let (program, parse_issues) = parse_file(&arena, source_file);
    assert!(parse_issues.is_none(), "Test '{name}' failed during parsing:\n{parse_issues:#?}");

    let resolver = NameResolver::new(&arena);
    let resolved_names = resolver.resolve(program);

    metadata.extend(scan_program(&arena, source_file, program, &resolved_names));

    populate_codebase(&mut metadata, &mut symbol_references, AtomSet::default(), HashSet::default());

    let guard = ArchitecturalGuard::new(settings);
    guard.check(&metadata, program, &resolved_names)
}

#[test]
pub fn test_extends_violation() {
    let code = indoc! {r"
        <?php
        namespace App\Core {}
        namespace App\Module {
            class MyClass extends \App\Core\BaseClass {}
        }
    "};
    let settings = deny_all_settings();
    let result = test_guard("extends_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].vector, BreachVector::Extends);
}

#[test]
pub fn test_implements_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {}

        namespace App\Module {
            class MyClass implements \App\Core\MyInterface {}
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("implements_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].vector, BreachVector::Implements);
}

// Test for UsageKind::ReturnType
#[test]
pub fn test_return_type_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {}
        namespace App\Module {
            function my_function(): \App\Core\MyType {}
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("return_type_violation", code, settings);

    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].vector, BreachVector::ReturnType);
}

#[test]
pub fn test_instantiation_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {}

        namespace App\Module {
            new \App\Core\MyClass();
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("instantiation_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].vector, BreachVector::Instantiation);
}

#[test]
pub fn test_static_method_call_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core { class Helper { public static function do() {} } }

        namespace App\Module {
            \App\Core\Helper::do();
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("static_method_call_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].vector, BreachVector::StaticMethodCall);
}

#[test]
pub fn test_interface_dependency_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core { interface ServiceInterface {} }

        namespace App\Module {
            class MyService implements \App\Core\ServiceInterface {}
        }
    "};
    let settings = deny_all_settings();
    let result = test_guard("interface_dependency_violation", code, settings);

    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].dependency_kind, PermittedDependencyKind::ClassLike);
}

#[test]
pub fn test_trait_dependency_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core { trait MyTrait {} }

        namespace App\Module {
            class MyClass { use \App\Core\MyTrait; }
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("trait_dependency_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].dependency_kind, PermittedDependencyKind::ClassLike);
}

#[test]
pub fn test_enum_dependency_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {
            enum MyEnum {}
        }

        namespace App\Module {
            function test(\App\Core\MyEnum $e) {}
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![],
            }],
            ..Default::default()
        },
        ..Default::default()
    };
    let result = test_guard("enum_dependency_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);

    assert_eq!(result.boundary_breaches[0].dependency_kind, PermittedDependencyKind::ClassLike);
}

#[test]
pub fn test_const_dependency_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {
            const MY_CONST = 1;
        }

        namespace App\Module {
            $a = \App\Core\MY_CONST;
        }
    "};

    let settings = deny_all_settings();
    let result = test_guard("const_dependency_violation", code, settings);

    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].dependency_kind, PermittedDependencyKind::Constant);
}

#[test]
pub fn test_native_type_is_allowed() {
    let code = indoc! {r"
        <?php

        namespace App\Module;

        use DateTime;
        use Exception;

        function test(DateTime $d): Exception {
            throw new Exception();
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![PermittedDependency::Dependency(Path::Native)],
            }],
            ..Default::default()
        },
        ..Default::default()
    };
    let result = test_guard("native_type_is_allowed", code, settings);
    assert!(result.is_empty(), "Expected no violations for native types, found: {:#?}", result.boundary_breaches);
}

#[test]
pub fn test_union_type_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {
            class A {}
        }

        namespace App\Domain {
            class B {}
        }

        namespace App\Module {
            use App\Core\A;
            use App\Domain\B;

            function test(A|B $ab) {
            }
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                    NamespacePath::Specific("App\\Domain\\".to_string()),
                )))],
            }],
            ..Default::default()
        },
        ..Default::default()
    };
    let result = test_guard("union_type_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 2, "Expected 2 violations for Core\\A");
    assert_eq!(result.boundary_breaches[0].dependency_fqn, "App\\Core\\A"); // `use`
    assert_eq!(result.boundary_breaches[1].dependency_fqn, "App\\Core\\A"); // parameter type
}

#[test]
pub fn test_intersection_type_violation() {
    let code = indoc! {r"
        <?php

        namespace App\Core {
            interface A {}
        }

        namespace App\Domain {
            interface B {}
        }

        namespace App\Module {
            use App\Domain\B;

            function test(\App\Core\A&B $ab) {}
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                    NamespacePath::Specific("App\\Domain\\".to_string()),
                )))],
            }],
            ..Default::default()
        },
        ..Default::default()
    };
    let result = test_guard("intersection_type_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1, "Expected 1 violation for Core\\A");
    assert_eq!(result.boundary_breaches[0].dependency_fqn, "App\\Core\\A");
}

#[test]
pub fn test_multiple_allowed_types_rule() {
    let code = indoc! {r"
        <?php

        namespace App\Vendor {
            class MyClass {}
            interface MyInterface {}
            trait MyTrait {}
        }

        namespace App\Module {
            use App\Vendor\MyClass;
            use App\Vendor\MyInterface;

            class Test implements MyInterface {
                public function create(): MyClass {
                    \App\Vendor\some_function(...);

                    return new MyClass();
                }
            }
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![PermittedDependency::DependencyOfKind {
                    path: Path::Selector(SymbolSelector::Pattern("App\\Vendor\\**".to_string())),
                    kinds: vec![PermittedDependencyKind::ClassLike],
                }],
            }],
            ..Default::default()
        },
        ..Default::default()
    };
    let result = test_guard("multiple_allowed_types_rule", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1, "Expected 1 violation for some_function");
    assert_eq!(result.boundary_breaches[0].dependency_fqn, "App\\Vendor\\some_function");
    assert_eq!(result.boundary_breaches[0].dependency_kind, PermittedDependencyKind::Function);
}

#[test]
pub fn test_global_namespace_dependency_violation() {
    let code = indoc! {r"
        <?php

        namespace { class GlobalClass {} }

        namespace App\Module {
            function test(\GlobalClass $g) {}
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            rules: vec![PerimeterRule {
                namespace: NamespacePath::Specific("App\\Module\\".to_string()),
                permit: vec![],
            }],
            ..Default::default()
        },

        ..Default::default()
    };
    let result = test_guard("global_namespace_dependency_violation", code, settings);
    assert_eq!(result.boundary_breaches.len(), 1);
    assert_eq!(result.boundary_breaches[0].dependency_fqn, "GlobalClass");
}

#[test]
pub fn test_ddd() {
    let code = indoc! {r"
        <?php

        namespace Symfony\Component\HttpFoundation {
            class Request {}
            class Response {}
        }

        namespace CarthageSoftware\Domain\Shared\Repository {
            interface RepositoryInterface {
                public function getOne(int $id): ?object;
            }
        }

        namespace CarthageSoftware\Domain\Blogging\Entity {
            class Post {}
        }

        namespace CarthageSoftware\Domain\Blogging\Repository {
            use CarthageSoftware\Domain\Blogging\Entity\Post;
            use CarthageSoftware\Domain\Shared\Repository\RepositoryInterface;

            interface PostRepositoryInterface extends RepositoryInterface {
                public function getOne(int $id): ?Post;
            }
        }

        namespace CarthageSoftware\Application\Blogging\Command {
            class CreatePostCommand {}
        }

        namespace CarthageSoftware\Application\Shared\Command {
            interface CommandBusInterface {
                public function dispatch(object $command): void;
            }
        }

        namespace CarthageSoftware\UI\Blogging\Web\Controller {
            use CarthageSoftware\Application\Blogging\Command\CreatePostCommand;
            use CarthageSoftware\Application\Shared\Command\CommandBusInterface;
            use CarthageSoftware\Domain\Blogging\Repository\PostRepositoryInterface;
            use CarthageSoftware\Domain\Blogging\Entity\Post;
            use Symfony\Component\HttpFoundation\Request;
            use Symfony\Component\HttpFoundation\Response;

            class PostController {
                public function __construct(private CommandBusInterface $commandBus) {}

                public function create(Request $request): Response {
                    $command = new CreatePostCommand();
                    $this->commandBus->dispatch($command);

                    return new Response();
                }
            }

            class ShowController {
                public function __construct(private PostRepositoryInterface $postRepository) {}

                public function show(int $id): ?Post {
                    return $this->postRepository->getOne($id);
                }
            }
        }
    "};

    let settings = Settings {
        perimeter: PerimeterSettings {
            layering: vec![
                NamespacePath::Specific("CarthageSoftware\\Domain\\".to_string()),
                NamespacePath::Specific("CarthageSoftware\\Application\\".to_string()),
                NamespacePath::Specific("CarthageSoftware\\UI\\".to_string()),
                NamespacePath::Specific("CarthageSoftware\\Infrastructure\\".to_string()),
            ],
            rules: vec![
                PerimeterRule {
                    namespace: NamespacePath::Specific("CarthageSoftware\\UI\\".to_string()),
                    permit: vec![
                        PermittedDependency::Dependency(Path::Native),
                        PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                            NamespacePath::Specific("CarthageSoftware\\Domain\\".to_string()),
                        ))),
                        PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                            NamespacePath::Specific("CarthageSoftware\\Application\\".to_string()),
                        ))),
                        PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                            NamespacePath::Specific("Symfony\\Component\\HttpFoundation\\".to_string()),
                        ))),
                    ],
                },
                PerimeterRule {
                    namespace: NamespacePath::Specific("CarthageSoftware\\Application\\".to_string()),
                    permit: vec![
                        PermittedDependency::Dependency(Path::Selector(SymbolSelector::Namespace(
                            NamespacePath::Specific("CarthageSoftware\\Domain\\".to_string()),
                        ))),
                        PermittedDependency::Dependency(Path::Native),
                    ],
                },
                PerimeterRule {
                    namespace: NamespacePath::Specific("CarthageSoftware\\Domain\\".to_string()),
                    permit: vec![
                        PermittedDependency::Dependency(Path::Self_),
                        PermittedDependency::Dependency(Path::Native),
                    ],
                },
                PerimeterRule {
                    namespace: NamespacePath::Specific("CarthageSoftware\\Domain\\".to_string()),
                    permit: vec![PermittedDependency::Dependency(Path::Native)],
                },
            ],
            ..Default::default()
        },
        ..Default::default()
    };

    let result = test_guard("test_ddd", code, settings);

    assert_eq!(result.boundary_breaches.len(), 0, "Expected no violations, found: {:#?}", result.boundary_breaches);
}