From d0f8999f719e70b40c6c34c937db065981a46204 Mon Sep 17 00:00:00 2001 From: Daniele Barbaro Date: Thu, 29 Oct 2026 21:37:12 +0100 Subject: [PATCH] feat(rules): report classes outside the layers --- CHANGELOG.md | 6 + README.md | 26 +++- config/clean-architecture.php | 16 ++ resources/boost/guidelines/core.blade.php | 8 +- .../clean-architecture-development/SKILL.md | 7 + src/Commands/MakeArchRulesCommand.php | 2 +- src/Concerns/BuildsArchRules.php | 138 +++++++++++++++--- .../ResolvesArchitectureDirectories.php | 11 +- stubs/config.stub | 16 ++ tests/Feature/GeneratedRulesTest.php | 19 +++ .../Commands/MakeArchRulesCommandTest.php | 47 ++++++ tests/Unit/Concerns/BuildsArchRulesTest.php | 84 +++++++++++ .../app/Http/Controllers/LegacyController.php | 8 + .../arch/app/Providers/AppServiceProvider.php | 8 + 14 files changed, 371 insertions(+), 25 deletions(-) create mode 100644 tests/fixtures/arch/app/Http/Controllers/LegacyController.php create mode 100644 tests/fixtures/arch/app/Providers/AppServiceProvider.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 58c26bf..b45f48e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to `laravel-clean-architecture` will be documented in this file. +## [Unreleased] + +### Added + +- `validation.rules.no_classes_outside_layers`, off by default. The generated rules only scanned the three layer directories, so code left in `app/Http`, `app/Models`, `app/Actions` and the other Laravel folders was never read and `phparkitect check` passed on an app only partly moved into the layers. With the rule on, every class under the root namespace (`App`, from `default_namespace` and the top level directory the layers share) has to reside in a layer or in a namespace listed under the new `validation.outside_layers_allowed`, which defaults to `['Providers']` since `bootstrap/providers.php` registers the service providers there. The generated file then scans the root directory once instead of the three layers, so no class is checked twice. `clean-arch:make-arch-rules` fails without writing when the rule is on and the layers do not share a top level directory, or when the allowlist holds an invalid entry + ## [3.7.1] - 2026-10-26 ### Fixed diff --git a/README.md b/README.md index 4a75219..dfa7615 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,7 @@ Two prefixes can point to the same directory, so `"Acme\\": "app/"` sits next to ### ✅ Validation rules -Every rule can be turned off by name under `validation.rules`. A rule set to `false` is left out of the config written by `clean-arch:make-arch-rules`. All of them except `no_commands_in_infrastructure` are enabled by default, and a project without a published config file gets the same set. +Every rule can be turned off by name under `validation.rules`. A rule set to `false` is left out of the config written by `clean-arch:make-arch-rules`. All of them except `no_commands_in_infrastructure` and `no_classes_outside_layers` are enabled by default, and a project without a published config file gets the same set. ```php 'validation' => [ @@ -352,6 +352,7 @@ Every rule can be turned off by name under `validation.rules`. A rule set to `fa 'no_observers_in_domain' => true, 'no_jobs_in_infrastructure' => true, 'no_commands_in_infrastructure' => false, + 'no_classes_outside_layers' => false, ], ], ``` @@ -368,6 +369,27 @@ Some projects send mail and notifications straight from an action, importing `Ap Values are relative to the infrastructure layer, so they keep working with custom `directories` and `default_namespace`. With the example above an action importing `App\Infrastructure\Mail\ArticleMail` passes, while one importing `App\Infrastructure\Http\Controllers\Controller` or `App\Infrastructure\Filament\ArticleResource` is still reported. The list is empty by default, and an empty list generates exactly the same `phparkitect.php` as before. An invalid entry (not a string, or empty) makes `clean-arch:make-arch-rules` fail without writing the file. After changing the key, regenerate the file with `php artisan clean-arch:make-arch-rules --force`. +#### 🧱 No classes outside the layers + +The other rules only read the three layer directories, so code left in `app/Http`, `app/Models`, `app/Actions` or `app/Filament` is never checked and `phparkitect check` stays green on an app that is half Laravel folders and half layers. `no_classes_outside_layers` closes that gap: every class under the root namespace has to reside in one of the three layers, or in a namespace listed under `validation.outside_layers_allowed`. + +```php +'validation' => [ + 'rules' => [ + 'no_classes_outside_layers' => true, + ], + 'outside_layers_allowed' => ['Providers'], +], +``` + +The rule is off by default, because a Laravel app reports its whole `app/Http` and `app/Models`, and everything else it ships outside the layers, until that code has been moved. + +The root is the top level directory the three layers share, `app` with the defaults, and its namespace is derived like the layer namespaces, so `App` or the configured `default_namespace`. Layers nested deeper, such as `app/Core/Domain`, still have `app` as their root, so `app/Http` keeps being checked. When the layers do not share a top level directory (for example `src/Domain` next to `app/Application`), or one of them sits directly in the project root, `clean-arch:make-arch-rules` fails with a message and writes nothing. Turn the rule off for such a layout. + +With the rule on, the generated file scans the root directory once instead of the three layer directories. The layer rules still only apply to their own namespaces, so every class is checked once and no violation is reported twice. + +`validation.outside_layers_allowed` lists namespaces relative to the root namespace that may stay outside the layers. It defaults to `['Providers']`: Laravel registers service providers from `bootstrap/providers.php`, and `make:provider` and the packages that publish a provider write them to `app/Providers`. Add the folders a framework or package discovers by convention and that you keep where they are, for example `'Policies'` (policy auto discovery looks next to the models), `'Livewire'` or `'Filament'`. An invalid entry (not a string, or empty) makes `clean-arch:make-arch-rules` fail without writing the file. + ### 📝 Custom validation messages `validation.custom_messages` controls whether `clean-arch:make-domain` generates the `messages()` method in the form requests it creates. It defaults to `true`. @@ -380,7 +402,7 @@ Values are relative to the infrastructure layer, so they keep working with custo Set it to `false` and the generated `Create*Request` and `Update*Request` classes will omit the `messages()` method entirely. The default `rules()` and `authorize()` methods are unaffected, and the output remains valid PHP either way. -Note the keys under `validation` serve different purposes. The `rules` subgroup and `application_infrastructure_allowed` are read by `clean-arch:make-arch-rules`, while `custom_messages` is read by `clean-arch:make-domain` at generation time. They are kept together so that a single published config file is the only place to look. +Note the keys under `validation` serve different purposes. The `rules` subgroup, `application_infrastructure_allowed` and `outside_layers_allowed` are read by `clean-arch:make-arch-rules`, while `custom_messages` is read by `clean-arch:make-domain` at generation time. They are kept together so that a single published config file is the only place to look. ### 🏗️ Optional base classes diff --git a/config/clean-architecture.php b/config/clean-architecture.php index 4badbd8..81dc096 100644 --- a/config/clean-architecture.php +++ b/config/clean-architecture.php @@ -37,6 +37,11 @@ | with --force. 'no_commands_in_infrastructure' is off by default: a | console command is an input adapter, like an HTTP controller, so it | lives in Infrastructure and calls an action for the business logic. + | 'no_classes_outside_layers' is off by default too: it reports every + | class of the directory the layers share (app/ with the defaults) + | that is not in a layer, such as the app/Http and app/Models Laravel + | ships with, so turn it on once the app has been moved into the + | layers. */ 'rules' => [ 'domain_no_application_imports' => true, @@ -45,6 +50,7 @@ 'no_observers_in_domain' => true, 'no_jobs_in_infrastructure' => true, 'no_commands_in_infrastructure' => false, + 'no_classes_outside_layers' => false, ], /* @@ -57,6 +63,16 @@ | default. Regenerate phparkitect.php with --force after changing it. */ 'application_infrastructure_allowed' => [], + + /* + | Namespaces that may stay outside the layers without breaking + | 'no_classes_outside_layers', relative to the root namespace, so + | ['Providers'] allows App\Providers. Providers is listed by default + | because bootstrap/providers.php registers the service providers + | there and Laravel's generators write them there. Regenerate + | phparkitect.php with --force after changing it. + */ + 'outside_layers_allowed' => ['Providers'], ], /* diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php index b3fe4fb..04664ed 100644 --- a/resources/boost/guidelines/core.blade.php +++ b/resources/boost/guidelines/core.blade.php @@ -101,8 +101,12 @@ - `generation.web_controller_path`: where `make-controller --web` writes, `Http/Controllers/Web` by default. API controllers always go to `Http/Controllers/Api`. -- `validation.rules`: the six rules written into `phparkitect.php`, each can be - turned off by name. `no_commands_in_infrastructure` is off by default. +- `validation.rules`: the seven rules written into `phparkitect.php`, each can + be turned off by name. `no_commands_in_infrastructure` and + `no_classes_outside_layers` are off by default. The latter reports every class + of the root namespace (app/ with the defaults) outside the three layers. +- `validation.outside_layers_allowed`: namespaces, relative to the root + namespace, that may stay outside the layers. `['Providers']` by default. - `validation.application_infrastructure_allowed`: infrastructure namespaces the application layer may import, relative to the infrastructure layer. Empty by default. diff --git a/resources/boost/skills/clean-architecture-development/SKILL.md b/resources/boost/skills/clean-architecture-development/SKILL.md index 8875cff..7c725ce 100644 --- a/resources/boost/skills/clean-architecture-development/SKILL.md +++ b/resources/boost/skills/clean-architecture-development/SKILL.md @@ -108,6 +108,13 @@ implement it one layer out and bind the two in a service provider. Do not widen Do not turn a rule off in `validation.rules` to silence a single violation: that hides every other violation of the same rule. +When `no_classes_outside_layers` is on, a class left in app/Http, app/Models, +app/Actions or any other folder outside the layers fails the check. Move it +into the layer it belongs to and update its namespace and every reference. +Only a folder that the framework or a package discovers by convention, such as +Providers or Policies, goes in `validation.outside_layers_allowed`, relative to +the root namespace. + ## Adopting the rules on an existing codebase vendor/bin/phparkitect generate-baseline diff --git a/src/Commands/MakeArchRulesCommand.php b/src/Commands/MakeArchRulesCommand.php index eaac58d..5a065f8 100644 --- a/src/Commands/MakeArchRulesCommand.php +++ b/src/Commands/MakeArchRulesCommand.php @@ -39,7 +39,7 @@ public function handle(): int { $this->resolveForce(); - if (($error = $this->allowlistError()) !== null) { + if (($error = $this->allowlistError() ?? $this->rootDirectoryError()) !== null) { $this->error($error); return self::FAILURE; diff --git a/src/Concerns/BuildsArchRules.php b/src/Concerns/BuildsArchRules.php index a25a4cb..acd284a 100644 --- a/src/Concerns/BuildsArchRules.php +++ b/src/Concerns/BuildsArchRules.php @@ -24,6 +24,18 @@ abstract protected function layerNamespace(string $layer): string; */ abstract protected function layerDirectory(string $layer): string; + /** + * Provided by ResolvesArchitectureDirectories. + */ + abstract protected function directoryNamespace(string $directory): string; + + /** + * Rules left out of the generated file unless the config turns them on. + * + * @var array + */ + protected array $optInArchRules = ['no_commands_in_infrastructure', 'no_classes_outside_layers']; + /** * One entry per enabled rule, each a complete `$rules[] = ...;` statement. * @@ -82,18 +94,97 @@ protected function archRules(): array $rules[] = $this->archRule($namespace, $expression, $because, $except); } + $root = $this->archRootDirectory(); + + if ($this->archRuleEnabled('no_classes_outside_layers') && $root !== null) { + $rootNamespace = rtrim($this->directoryNamespace($root), '\\'); + + $rules[] = $this->archRule( + $rootNamespace, + $this->outsideLayersExpression($rootNamespace, [$domain, $application, $infrastructure]), + 'every class of the application belongs to one of the three layers' + ); + } + return $rules; } + /** + * The directory the three layers share, the first segment of their paths + * (`app` with the defaults), or null when they do not share one. + * + * Only the top level directory is used, not the closest common parent, so + * layers configured under `app/Core` still have `app/Http` and the other + * Laravel folders checked. + */ + protected function archRootDirectory(): ?string + { + $roots = []; + + foreach (['domain', 'application', 'infrastructure'] as $layer) { + $segments = explode('/', $this->layerDirectory($layer)); + + // A layer at the top of the project would make the base path, vendor included, the root. + if (count($segments) < 2) { + return null; + } + + $roots[$segments[0]] = true; + } + + return count($roots) === 1 ? (string) array_key_first($roots) : null; + } + + /** + * Why 'no_classes_outside_layers' cannot be generated, or null when it can. + */ + protected function rootDirectoryError(): ?string + { + if (! $this->archRuleEnabled('no_classes_outside_layers') || $this->archRootDirectory() !== null) { + return null; + } + + $directories = implode(', ', array_map($this->layerDirectory(...), ['domain', 'application', 'infrastructure'])); + + return "validation.rules.no_classes_outside_layers needs the three layer directories inside one top level directory, such as app/, got {$directories}. " + . 'Move the layers under one directory or turn the rule off.'; + } + + /** + * The layers, followed by the allowed namespaces, as the places a class + * of the root namespace may reside in. + * + * @param array $layers + */ + protected function outsideLayersExpression(string $root, array $layers): string + { + /** @var array $segments */ + $segments = config('clean-architecture.validation.outside_layers_allowed', ['Providers']); + $allowed = array_map( + fn (string $segment): string => $root . '\\' . trim(str_replace('/', '\\', $segment), '\\'), + $segments + ); + + return 'new ResideInOneOfTheseNamespaces(' . implode(', ', array_map($this->archLiteral(...), [...$layers, ...$allowed])) . ')'; + } + /** * The `$config->add()` calls, one class set per configured layer directory. * * Scanning the layers instead of the whole application keeps projects that * moved the directories working, and leaves the rest of the codebase out of - * the scan. + * the scan. With 'no_classes_outside_layers' on, the directory the layers + * share is scanned instead, once, so no class is checked twice. */ protected function archClassSets(): string { + $root = $this->archRootDirectory(); + + // The layers sit inside the root, so scanning it alone checks every class once. + if ($this->archRuleEnabled('no_classes_outside_layers') && $root !== null) { + return " \$config->add(ClassSet::fromDir(__DIR__ . '/{$root}'), ...\$rules);"; + } + $calls = []; foreach (['domain', 'application', 'infrastructure'] as $layer) { @@ -182,28 +273,35 @@ protected function allowedInfrastructureNamespaces(string $infrastructure): arra } /** - * Why the allowlist cannot be used, or null when it can. + * Why an allowlist cannot be used, or null when it can. * * Invalid entries are reported rather than dropped: skipping one silently - * would flag imports the user believes are allowed, and an entry that - * trims to nothing would exclude the whole infrastructure layer. + * would flag classes the user believes are allowed, and an entry that + * trims to nothing would allow the whole layer or root namespace. */ protected function allowlistError(): ?string { - if (! $this->archRuleEnabled('application_no_infrastructure_imports')) { - return null; - } + $allowlists = [ + 'application_no_infrastructure_imports' => ['application_infrastructure_allowed', [], 'infrastructure namespace segments', 'Mail'], + 'no_classes_outside_layers' => ['outside_layers_allowed', ['Providers'], 'namespace segments relative to the root namespace', 'Providers'], + ]; + + foreach ($allowlists as $rule => [$name, $default, $description, $example]) { + if (! $this->archRuleEnabled($rule)) { + continue; + } - $key = 'validation.application_infrastructure_allowed'; - $allowed = config("clean-architecture.{$key}", []); + $key = "validation.{$name}"; + $allowed = config("clean-architecture.{$key}", $default); - if (! is_array($allowed)) { - return "{$key} must be a list of infrastructure namespace segments, got " . var_export($allowed, true) . '.'; - } + if (! is_array($allowed)) { + return "{$key} must be a list of {$description}, got " . var_export($allowed, true) . '.'; + } - foreach ($allowed as $segment) { - if (! is_string($segment) || trim(str_replace('/', '\\', $segment), '\\') === '') { - return "{$key} contains an invalid entry " . var_export($segment, true) . ', expected a non empty namespace segment such as \'Mail\'.'; + foreach ($allowed as $segment) { + if (! is_string($segment) || trim(str_replace('/', '\\', $segment), '\\') === '') { + return "{$key} contains an invalid entry " . var_export($segment, true) . ", expected a non empty namespace segment such as '{$example}'."; + } } } @@ -212,13 +310,15 @@ protected function allowlistError(): ?string /** * A rule is enabled unless the config says otherwise, so an unpublished - * config still generates the default set. 'no_commands_in_infrastructure' - * is the exception and has to be turned on explicitly. + * config still generates the default set. The rules in $optInArchRules + * are the exception and have to be turned on explicitly. */ protected function archRuleEnabled(string $rule): bool { - // The package does not merge its config, so the opt-in rule needs its default here too. - return config("clean-architecture.validation.rules.{$rule}", $rule !== 'no_commands_in_infrastructure') !== false; + // The package does not merge its config, so the opt-in rules need their default here too. + $default = ! in_array($rule, $this->optInArchRules, true); + + return config("clean-architecture.validation.rules.{$rule}", $default) !== false; } /** diff --git a/src/Concerns/ResolvesArchitectureDirectories.php b/src/Concerns/ResolvesArchitectureDirectories.php index edcb91a..d7d8b8c 100644 --- a/src/Concerns/ResolvesArchitectureDirectories.php +++ b/src/Concerns/ResolvesArchitectureDirectories.php @@ -94,7 +94,16 @@ protected function webControllerNamespace(): string */ protected function layerNamespace(string $layer): string { - $segments = explode('/', $this->layerDirectory($layer)); + return $this->directoryNamespace($this->layerDirectory($layer)); + } + + /** + * Namespace of a directory relative to the base path, with a trailing + * separator, derived the same way as the layer namespaces. + */ + protected function directoryNamespace(string $directory): string + { + $segments = explode('/', trim($directory, '/')); if (strtolower((string) reset($segments)) === 'app') { array_shift($segments); diff --git a/stubs/config.stub b/stubs/config.stub index 00eaa8f..ce6c08a 100644 --- a/stubs/config.stub +++ b/stubs/config.stub @@ -37,6 +37,11 @@ return [ | with --force. 'no_commands_in_infrastructure' is off by default: a | console command is an input adapter, like an HTTP controller, so it | lives in Infrastructure and calls an action for the business logic. + | 'no_classes_outside_layers' is off by default too: it reports every + | class of the directory the layers share (app/ with the defaults) + | that is not in a layer, such as the app/Http and app/Models Laravel + | ships with, so turn it on once the app has been moved into the + | layers. */ 'rules' => [ 'domain_no_application_imports' => true, @@ -45,6 +50,7 @@ return [ 'no_observers_in_domain' => true, 'no_jobs_in_infrastructure' => true, 'no_commands_in_infrastructure' => false, + 'no_classes_outside_layers' => false, ], /* @@ -57,6 +63,16 @@ return [ | default. Regenerate phparkitect.php with --force after changing it. */ 'application_infrastructure_allowed' => [], + + /* + | Namespaces that may stay outside the layers without breaking + | 'no_classes_outside_layers', relative to the root namespace, so + | ['Providers'] allows App\Providers. Providers is listed by default + | because bootstrap/providers.php registers the service providers + | there and Laravel's generators write them there. Regenerate + | phparkitect.php with --force after changing it. + */ + 'outside_layers_allowed' => ['Providers'], ], /* diff --git a/tests/Feature/GeneratedRulesTest.php b/tests/Feature/GeneratedRulesTest.php index b3e09a0..3eda008 100644 --- a/tests/Feature/GeneratedRulesTest.php +++ b/tests/Feature/GeneratedRulesTest.php @@ -131,6 +131,25 @@ function runPhparkitect(string $config, string $autoload): array ->and($result['output'])->not->toContain('Fatal error'); }); + it('leaves classes outside the layers alone while the rule is off', function () { + $result = runPhparkitect($this->config, fixtureDirectory() . '/autoload.php'); + + expect($result['output'])->not->toContain('LegacyController'); + }); + + it('reports a class outside the layers, once, when the rule is on', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + + $result = runPhparkitect(generateFixtureConfig(), fixtureDirectory() . '/autoload.php'); + + expect($result['exitCode'])->toBe(1) + ->and($result['output']) + ->toContain('ArchFixture\Http\Controllers\LegacyController has 1 violations') + ->toContain('should reside in one of these namespaces: ArchFixture\Domain, ArchFixture\Application, ArchFixture\Infrastructure, ArchFixture\Providers') + ->not->toContain('AppServiceProvider') + ->toContain('8 violations detected'); + }); + it('fails loudly instead of passing silently when autoloading does not resolve', function () { $result = runPhparkitect($this->config, fixtureDirectory() . '/autoload-broken.php'); diff --git a/tests/Unit/Commands/MakeArchRulesCommandTest.php b/tests/Unit/Commands/MakeArchRulesCommandTest.php index ee1bb45..7e9754a 100644 --- a/tests/Unit/Commands/MakeArchRulesCommandTest.php +++ b/tests/Unit/Commands/MakeArchRulesCommandTest.php @@ -95,4 +95,51 @@ expect(File::get($this->path))->toContain("ClassSet::fromDir(__DIR__ . '/src/Domain')"); }); + + it('writes the outside layers rule and scans the root directory when enabled', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + + $this->artisan('clean-arch:make-arch-rules')->assertExitCode(0); + + $contents = File::get($this->path); + + expect($contents) + ->toContain("->that(new ResideInOneOfTheseNamespaces('App'))") + ->toContain("ClassSet::fromDir(__DIR__ . '/app')") + ->not->toContain("ClassSet::fromDir(__DIR__ . '/app/Domain')") + ->and(token_get_all($contents, TOKEN_PARSE))->toBeArray(); + }); + + it('fails without writing when the layers share no top level directory', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + config()->set('clean-architecture.directories.domain', 'src/Domain'); + + $this->artisan('clean-arch:make-arch-rules') + ->expectsOutputToContain('src/Domain, app/Application, app/Infrastructure') + ->assertExitCode(1); + + expect(File::exists($this->path))->toBeFalse(); + }); + + it('rejects an invalid outside layers allowlist without writing the config', function (mixed $allowed) { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + config()->set('clean-architecture.validation.outside_layers_allowed', $allowed); + + $this->artisan('clean-arch:make-arch-rules') + ->expectsOutputToContain('validation.outside_layers_allowed') + ->assertExitCode(1); + + expect(File::exists($this->path))->toBeFalse(); + })->with([ + 'a string' => ['Providers'], + 'an empty entry' => [['Providers', '']], + 'an integer entry' => [[42]], + ]); + + it('ignores the outside layers allowlist and the directories while the rule is off', function () { + config()->set('clean-architecture.validation.outside_layers_allowed', 'Providers'); + config()->set('clean-architecture.directories.domain', 'src/Domain'); + + $this->artisan('clean-arch:make-arch-rules')->assertExitCode(0); + }); }); diff --git a/tests/Unit/Concerns/BuildsArchRulesTest.php b/tests/Unit/Concerns/BuildsArchRulesTest.php index 9435a0a..40fb162 100644 --- a/tests/Unit/Concerns/BuildsArchRulesTest.php +++ b/tests/Unit/Concerns/BuildsArchRulesTest.php @@ -39,6 +39,23 @@ function buildAutoloadGuard(): string return $method->invoke($subject); } +/** + * Call the protected class set builder on an anonymous class that uses the trait. + */ +function buildArchClassSets(): string +{ + $subject = new class + { + use BuildsArchRules; + use ResolvesArchitectureDirectories; + }; + + $method = new ReflectionMethod($subject, 'archClassSets'); + $method->setAccessible(true); + + return $method->invoke($subject); +} + describe('BuildsArchRules', function () { it('builds a dependency rule for the domain layer', function () { $rules = buildArchRules(); @@ -196,4 +213,71 @@ function buildAutoloadGuard(): string expect(buildArchRules()[0]) ->toContain("new ResideInOneOfTheseNamespaces('Acme\\\\Core\\\\Domain')"); }); + + it('leaves the outside layers rule out by default', function () { + expect(implode("\n", buildArchRules()))->not->toContain("ResideInOneOfTheseNamespaces('App')"); + }); + + it('keeps every class of the root namespace in a layer or an allowed namespace when enabled', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + + $expected = <<<'PHP' + $rules[] = Rule::allClasses() + ->that(new ResideInOneOfTheseNamespaces('App')) + ->should(new ResideInOneOfTheseNamespaces('App\\Domain', 'App\\Application', 'App\\Infrastructure', 'App\\Providers')) + ->because('every class of the application belongs to one of the three layers'); + PHP; + + expect(buildArchRules()[5])->toBe($expected); + }); + + it('resolves the allowed outside namespaces against the root namespace', function () { + config()->set('clean-architecture.default_namespace', 'Acme'); + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + config()->set('clean-architecture.validation.outside_layers_allowed', ['/Providers/', 'Livewire']); + + expect(buildArchRules()[5]) + ->toContain("->that(new ResideInOneOfTheseNamespaces('Acme'))") + ->toContain("'Acme\\\\Providers', 'Acme\\\\Livewire'))"); + }); + + it('allows nothing outside the layers with an empty allowlist', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + config()->set('clean-architecture.validation.outside_layers_allowed', []); + + expect(buildArchRules()[5]) + ->toContain("->should(new ResideInOneOfTheseNamespaces('App\\\\Domain', 'App\\\\Application', 'App\\\\Infrastructure'))"); + }); + + it('takes the top level directory as the root when the layers are nested', function () { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + config()->set('clean-architecture.directories.domain', 'app/Core/Domain'); + + expect(buildArchRules()[5]) + ->toContain("->that(new ResideInOneOfTheseNamespaces('App'))") + ->toContain("'App\\\\Core\\\\Domain'") + ->and(buildArchClassSets())->toBe(" \$config->add(ClassSet::fromDir(__DIR__ . '/app'), ...\$rules);"); + }); + + it('scans the root directory once instead of the layers when the outside layers rule is enabled', function () { + expect(substr_count(buildArchClassSets(), 'ClassSet::fromDir'))->toBe(3); + + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + + expect(buildArchClassSets())->toBe(" \$config->add(ClassSet::fromDir(__DIR__ . '/app'), ...\$rules);"); + }); + + it('skips the outside layers rule when the layers share no top level directory', function (array $directories) { + config()->set('clean-architecture.validation.rules.no_classes_outside_layers', true); + + foreach ($directories as $layer => $directory) { + config()->set("clean-architecture.directories.{$layer}", $directory); + } + + expect(buildArchRules())->toHaveCount(5) + ->and(substr_count(buildArchClassSets(), 'ClassSet::fromDir'))->toBe(3); + })->with([ + 'different roots' => [['domain' => 'src/Domain']], + 'top level layers' => [['domain' => 'Domain', 'application' => 'Application', 'infrastructure' => 'Infrastructure']], + ]); }); diff --git a/tests/fixtures/arch/app/Http/Controllers/LegacyController.php b/tests/fixtures/arch/app/Http/Controllers/LegacyController.php new file mode 100644 index 0000000..bc0c877 --- /dev/null +++ b/tests/fixtures/arch/app/Http/Controllers/LegacyController.php @@ -0,0 +1,8 @@ +