Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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' => [
Expand All @@ -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,
],
],
```
Expand All @@ -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`.
Expand All @@ -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

Expand Down
16 changes: 16 additions & 0 deletions config/clean-architecture.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -45,6 +50,7 @@
'no_observers_in_domain' => true,
'no_jobs_in_infrastructure' => true,
'no_commands_in_infrastructure' => false,
'no_classes_outside_layers' => false,
],

/*
Expand All @@ -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'],
],

/*
Expand Down
8 changes: 6 additions & 2 deletions resources/boost/guidelines/core.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/MakeArchRulesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
138 changes: 119 additions & 19 deletions src/Concerns/BuildsArchRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<int, string>
*/
protected array $optInArchRules = ['no_commands_in_infrastructure', 'no_classes_outside_layers'];

/**
* One entry per enabled rule, each a complete `$rules[] = ...;` statement.
*
Expand Down Expand Up @@ -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<int, string> $layers
*/
protected function outsideLayersExpression(string $root, array $layers): string
{
/** @var array<int, string> $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) {
Expand Down Expand Up @@ -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}'.";
}
}
}

Expand All @@ -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;
}

/**
Expand Down
11 changes: 10 additions & 1 deletion src/Concerns/ResolvesArchitectureDirectories.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading