NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
Packagist
Packagist, #2099 most downloaded on Packagist
Configurable PHP architecture guards — define your layers and rules, then keep them enforced
Latest stable
0.21.8
Last release 13 days ago
08 Nov 2026
Ships on a steady schedule
a new release about every 8 days
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
6 months old
251 releases · first in 2026
Drag across the ruler to compare, or tap a release to open it.
perf: Fork parallel workers with pcntl_fork when available, fallback to proc_open by @samsonasik in #553
Full Changelog: 0.21.7...0.21.8
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.7...0.21.8
Released: StructArmed 0.21.8 Latest
Latest
Compare
Your coding agent can read these notes before it upgrades. Set up the MCP server →
One column per month.
fix: Skip init when a structarmed.dist.php config already exists by @samsonasik in #552
Full Changelog: 0.21.6...0.21.7
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.6...0.21.7
refactor: Read class-like docblock once for @api and @internal tags by @samsonasik in #551
@api and @internal tags by @samsonasik in #551Full Changelog: 0.21.5...0.21.6
@api and @internal tags by @samsonasik in https://github.com/boundwize/structarmed/pull/551Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.5...0.21.6
refactor: Clean up redundant checks in ParallelAnalysisNodeExtractor by @samsonasik in #546
Full Changelog: 0.21.4...0.21.5
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.4...0.21.5
fix: Match language constructs case-insensitively in usesLanguageConstruct() by @samsonasik in #543
Full Changelog: 0.21.3...0.21.4
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.3...0.21.4
[dx] Mention promoted members in ApiMayNotExposeInternalRule violation message by @samsonasik in #542
Full Changelog: 0.21.2...0.21.3
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.2...0.21.3
[dx] Make isPromoted = true flag on Param as well by @samsonasik in #541
Full Changelog: 0.21.1...0.21.2
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.1...0.21.2
[dx] Add isPromoted to ClassSignature to tell promoted properties from declared ones by @samsonasik in #540
Full Changelog: 0.21.0...0.21.1
Full Changelog: https://github.com/boundwize/structarmed/compare/0.21.0...0.21.1
StructArmed 0.21.0 introduces a new Enum preset, stronger API stability checks, signature type analysis for custom rules, and improved enum formatting
StructArmed 0.21.0 introduces a new Enum preset, stronger API stability checks, signature type analysis for custom rules, and improved enum formatting support.
This release introduces:
Preset::ENUM() for validating string-backed enum case values;ApiMayNotExposeInternalRule for preventing public APIs from exposing internal types;ClassSignature and SignatureTypesAwareRuleInterface for analyzing member signature types;EnumCaseMustBeOnOwnLineRule in the PER preset;StructArmed introduces a new preset for validating string-backed enum case values:
Preset::ENUM()The preset includes two new rules:
EnumCaseValueMustNotBeEmptyRule — prevents empty string-backed enum values.EnumCaseValueMustNotHaveSurroundingWhitespaceRule — prevents leading or trailing whitespace in string-backed enum values.For example:
enum Status: string
{
case Pending = '';
case Active = ' active ';
case Completed = 'completed';
}The first two cases produce violations, while Completed is valid.
The rules check statically resolved string-backed values. Pure enums and integer-backed enums are unaffected.
These rules do not support --fix, as changing backing values could break existing APIs or persisted data.
Enable the preset with:
use Boundwize\StructArmed\Preset\Preset;
// In your architecture configuration:
->withPreset(Preset::ENUM())Or initialize a new configuration:
vendor/bin/structarmed init --preset=enumThe Stability preset now includes ApiMayNotExposeInternalRule, preventing @api declarations from exposing @internal types through public or protected signatures.
For example:
/** @internal */
class InternalService
{
}
/** @api */
class PublicService
{
public function getService(): InternalService
{
return new InternalService();
}
}The rule reports an architecture violation because the public method exposes an internal implementation.
The rule checks:
Private implementation details remain unrestricted, except when exposed through a public or protected constructor parameter.
Only types within the scanned project are checked, since external declarations may not have available PHPDoc information.
StructArmed introduces ClassSignature and SignatureTypesAwareRuleInterface for analyzing types referenced in class-like member signatures.
Each ClassSignature provides:
type — fully qualified referenced type;name — originating property, parameter, or method;kind — property, parameter, or method;visibility — public, protected, or private;line — source line.Custom rules can implement SignatureTypesAwareRuleInterface to access signature information through $classNode->signatures.
For example, prevent public repository methods from returning Doctrine's QueryBuilder:
<?php
declare(strict_types=1);
namespace App\Architecture\Rules;
use Boundwize\StructArmed\Analyser\ClassNode;
use Boundwize\StructArmed\Analyser\ClassSignature;
use Boundwize\StructArmed\Rule\RuleViolation;
use Boundwize\StructArmed\Rule\SignatureTypesAwareRuleInterface;
use Doctrine\ORM\QueryBuilder;
final readonly class MayNotReturnQueryBuilderRule implements SignatureTypesAwareRuleInterface
{
public function appliesTo(ClassNode $classNode): bool
{
return $classNode->nameEndsWith('Repository');
}
public function evaluate(ClassNode $classNode): ?RuleViolation
{
foreach ($classNode->signatures as $signature) {
if (
$signature->kind !== ClassSignature::METHOD
|| $signature->visibility !== 'public'
|| $signature->type !== QueryBuilder::class
) {
continue;
}
return new RuleViolation(
message: 'Public repository methods must not return QueryBuilder',
file: $classNode->file,
line: $signature->line,
className: $classNode->className,
layer: $classNode->layer,
);
}
return null;
}
}With this rule, the following method produces a violation:
final class UserRepository
{
public function createQuery(): QueryBuilder
{
// ...
}
}This allows repositories to use QueryBuilder internally without exposing it through their public APIs.
Signature collection is enabled only when an active rule implements SignatureTypesAwareRuleInterface, avoiding unnecessary analysis overhead and cache storage.
The collector supports nullable, union, intersection, and DNF types, including constructor-promoted properties.
The PER preset now includes EnumCaseMustBeOnOwnLineRule, requiring each enum case to be declared on its own line.
For example:
enum Status
{
case Pending; case Active;
}The rule supports automatic fixing:
vendor/bin/structarmed analyse --fixResult:
enum Status
{
case Pending;
case Active;
}The fixer preserves associated comments when moving enum cases, including comments on shared lines.
EnumCaseNode::sharesLine for detecting enum cases that share a line with another member or enum brace.ClassSignature support in #524 and #526.Full Changelog: 0.20.5...0.21.0
perf: Return cached nodes early when no file needs parsing by @samsonasik in #535
Full Changelog: 0.20.4...0.20.5
Full Changelog: https://github.com/boundwize/structarmed/compare/0.20.4...0.20.5
perf: Check each allowed layer–dependency pair once in the ruleset loop by @samsonasik in #534
Full Changelog: 0.20.3...0.20.4
Full Changelog: https://github.com/boundwize/structarmed/compare/0.20.3...0.20.4
perf: Skip per-file realpath() in PhpFileCollector by walking from the canonical root by @samsonasik in #532
Full Changelog: 0.20.2...0.20.3
Full Changelog: https://github.com/boundwize/structarmed/compare/0.20.2...0.20.3
Fix Path::isAbsolute() treating non-letter prefixes like "1:/" as Windows drives by @samsonasik in #528
Full Changelog: 0.20.1...0.20.2
Full Changelog: https://github.com/boundwize/structarmed/compare/0.20.1...0.20.2
Fix class-like string matching: reject trailing newline and invalid static callable method names by @samsonasik in #527
Full Changelog: 0.20.0...0.20.1
Full Changelog: https://github.com/boundwize/structarmed/compare/0.20.0...0.20.1
StructArmed 0.20.0 introduces a new Stability preset, modular architecture configuration, and an option to run analysis without persistent caching.
StructArmed 0.20.0 introduces a new Stability preset, modular architecture configuration, and an option to run analysis without persistent caching.
This release introduces:
Preset::STABILITY() for protecting public APIs from internal implementation details;isApi and isInternal properties on ClassNode for custom rule development;Architecture::import() for splitting architecture configuration across multiple files;--no-cache for running analysis without persistent caching;StructArmed introduces a new preset for enforcing API stability:
Preset::STABILITY()The preset includes two new rules:
ApiMayNotBeInternalRule — prevents declarations from being marked with both @api and @internal.ApiMayNotExtendInternalRule — prevents @api classes and interfaces from extending @internal declarations, directly or through inheritance.For example:
/** @internal */
class InternalService
{
}
/** @api */
class PublicService extends InternalService
{
}The Stability preset reports an architecture violation because a public API extends an internal implementation.
Enable the preset with:
use Boundwize\StructArmed\Preset\Preset;
->withPreset(Preset::STABILITY())Or initialize a new configuration:
vendor/bin/structarmed init --preset=stabilityClassNode now exposes two new boolean properties:
$classNode->isApi — indicates whether the declaration has an @api PHPDoc tag.$classNode->isInternal — indicates whether the declaration has an @internal PHPDoc tag.These properties are available to custom architecture rules, making it easier to enforce project-specific API stability and visibility conventions.
For example:
public function appliesTo(ClassNode $classNode): bool
{
return $classNode->isApi && ! $classNode->isInternal;
}The properties are populated automatically during analysis for scanned class-like declarations, including classes, interfaces, traits, and enums.
StructArmed now supports organizing architecture configuration across multiple files using Architecture::import().
For example:
use Boundwize\StructArmed\Architecture;
return Architecture::define()
->import(__DIR__ . '/module/Foo/structarmed.php')
->import(__DIR__ . '/module/Bar/structarmed.php');Each imported file returns a callable that receives the root Architecture instance:
use Boundwize\StructArmed\Architecture;
return static function (Architecture $architecture): void {
$architecture->layer('Foo', 'module/Foo/src/');
};This allows architecture rules and layers to be organized by module while sharing the same configuration.
Imported configurations support:
This makes StructArmed easier to configure and maintain in modular applications and larger projects.
StructArmed introduces a new CLI option:
vendor/bin/structarmed analyse --no-cacheThis option runs analysis without reading from or writing to the persistent analysis cache.
It is useful for debugging, validating uncached analysis, and environments where persistent caching is not desired.
The option supports both sequential and parallel analysis.
--no-cache cannot be combined with --clear-cache.
.class.php files.--no-cache analysis.--no-cache option in #507.ClassNode API/internal detection in #510.--no-cache analysis in #513..class.php files in #516.Full Changelog: 0.19.10...0.20.0
perf: Wait for parallel workers with stream_select() when progress is disabled by @samsonasik in #520
Full Changelog: 0.19.9...0.19.10
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.9...0.19.10
perf: Speed up violation sorting and function usage marking by @samsonasik in #515
Full Changelog: 0.19.8...0.19.9
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.8...0.19.9
fix: Avoid treating function and constant names as class references by @samsonasik in #514
Full Changelog: 0.19.7...0.19.8
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.7...0.19.8
fix: Sort violations by file and line so reports and baselines are stable across runs by @samsonasik in #512
Full Changelog: 0.19.6...0.19.7
[docs] Add more example on withPresets() by @samsonasik in #509
Full Changelog: 0.19.5...0.19.6
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.5...0.19.6
perf: Optimize violation fixing by skipping non-fixable rules and avoiding array shifts by @samsonasik in #503
Full Changelog: 0.19.4...0.19.5
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.4...0.19.5
fix: File rules honour the user defined Source layer when a preset has no source paths by @samsonasik in #502
Full Changelog: 0.19.3...0.19.4
perf: Cluster large files into one worker and write node cache incrementally by @samsonasik in #501
Full Changelog: 0.19.2...0.19.3
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.2...0.19.3
perf: Store only the content hash in per-file cache payload metadata by @samsonasik in #498
Full Changelog: 0.19.1...0.19.2
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.1...0.19.2
perf: Halve coordinator memory by adding __unserialize() to analysis nodes by @samsonasik in #497
Full Changelog: 0.19.0...0.19.1
Full Changelog: https://github.com/boundwize/structarmed/compare/0.19.0...0.19.1
StructArmed 0.19.0 introduces configurable project base paths and a new architecture rule for restricting constant usage.
StructArmed 0.19.0 introduces configurable project base paths and a new architecture rule for restricting constant usage.
This release introduces:
--basepath and its -d alias for analysing projects from a separate working directory;MayNotUseConstantRule for restricting constant usage within architecture layers;STDIN, STDOUT, and STDERR;StructArmed now supports specifying the project root through --basepath or its short alias -d.
This is useful when StructArmed is installed in a separate tools directory instead of the project's root directory.
For example:
composer.json
src/
tests/
tools/
└── structarmed/
├── composer.json
├── structarmed.php
└── vendor/
From tools/structarmed, run:
vendor/bin/structarmed analyse --basepath=../../Or use the shorter form:
vendor/bin/structarmed analyse -d ../../The specified base path is used for resolving:
composer.json and PSR-4 mappings;Configuration discovery checks the current working directory first, followed by the specified base path. An explicit --config remains relative to the current working directory.
The option also works with cache clearing:
vendor/bin/structarmed --basepath=../../ --clear-cacheCLI options may be specified before or after the command.
This makes StructArmed easier to integrate into projects that keep development tools and their dependencies separate from the application.
StructArmed introduces:
MayNotUseConstantRuleThis rule prevents classes, traits, and enums in a specified architecture layer from using a forbidden constant.
For example:
use Boundwize\StructArmed\Rule\Rules\Usage\MayNotUseConstantRule;
->rule(
'domain_no_php_eol',
new MayNotUseConstantRule(
layer: 'Domain',
constant: 'PHP_EOL',
),
)The rule supports global and namespaced constants:
new MayNotUseConstantRule(
layer: 'Domain',
constant: 'Vendor\\Config\\DEBUG',
)Constant names are matched case-sensitively, while namespace names are matched case-insensitively.
The rule also handles PHP's runtime fallback behavior for unqualified constants inside namespaces.
The DDD preset now prevents the Domain layer from directly using these constants:
STDINSTDOUTSTDERRThese restrictions are enabled automatically through:
Preset::DDD()This helps keep domain logic independent of direct console input and output.
RuleViolationCollection::forLayer() and toJson() methods.fidry/cpu-core-counter dependency to ^1.4.MayNotUseConstantRule and DDD preset restrictions in #495.--basepath and -d in #496.RuleViolationCollection::forLayer() and toJson() methods in #476.fidry/cpu-core-counter to ^1.4 in #490.Full Changelog: 0.18.11...0.19.0
Reduce temporary memory usage when grouping analysis cache nodes by @samsonasik in #493
Full Changelog: 0.18.10...0.18.11
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.10...0.18.11
Improve analyser performance by reducing repeated function name normalization by @samsonasik in #491
Full Changelog: 0.18.9...0.18.10
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.9...0.18.10
perf: Optimize ruleset expansion and simplify dependency checks by @samsonasik in #489
Full Changelog: 0.18.8...0.18.9
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.8...0.18.9
Fix MayNotUseClassRule to match class names case insensitively by @samsonasik in #485
Full Changelog: 0.18.7...0.18.8
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.7...0.18.8
perf: Preserve function analysis performance while retaining namespace fallback fixes by @samsonasik in #483
Full Changelog: 0.18.6...0.18.7
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.6...0.18.7
Fix MayNotCallFunctionRule missing unqualified calls to same namespace functions declared in another file by @samsonasik in #482
Full Changelog: 0.18.5...0.18.6
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.5...0.18.6
Fix conditional namespaced function suppressing global function fallback usage by @samsonasik in #481
Full Changelog: 0.18.4...0.18.5
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.4...0.18.5
fix: Resolve unqualified function calls without short name collisions by @samsonasik in #480
Full Changelog: 0.18.3...0.18.4
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.3...0.18.4
fix: Recognise global function fallback in namespaced top level calls by @samsonasik in #479
Full Changelog: 0.18.2...0.18.3
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.2...0.18.3
perf: Clean up redundant call type checks in AnalysisNodeCollector by @samsonasik in #470
Full Changelog: 0.18.1...0.18.2
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.1...0.18.2
perf: Skip garbage collection during analyse() by @samsonasik in #466
Full Changelog: 0.18.0...0.18.1
Full Changelog: https://github.com/boundwize/structarmed/compare/0.18.0...0.18.1
StructArmed 0.18.0 improves CI integration and expands YAGNI analysis to named functions.
StructArmed 0.18.0 improves CI integration and expands YAGNI analysis to named functions.
This release introduces:
--report=github;Architecture::layer();Boundwize\StructArmed\Rule\UsedFunctionAwareRuleInterface and the new fixable MustBeUsedFunctionRule.StructArmed can now report violations directly as GitHub Actions annotations:
vendor/bin/structarmed analyse --report=githubEach violation is emitted as a GitHub workflow error annotation, so violations appear directly on affected files and lines in pull requests.
The regular console report is appended after the annotations, so View details still opens a readable StructArmed report in the job log.
For example:
- name: Run StructArmed
run: vendor/bin/structarmed analyse --report=githubThe GitHub report intentionally exits with 0, allowing violations to be surfaced as annotations without failing the job itself.
Use the regular console or json report when violations should fail the job.
The github and json reports also disable the progress bar automatically.
Architecture::layer() now supports excluding one or more nested paths from a layer.
For example:
return Architecture::define()
->layer(
'Logger',
'src/Logger/',
excludePath: 'src/Logger/Factory/',
)
->layer('Factory', 'src/Logger/Factory/');Files under src/Logger/Factory/ now belong to Factory without also belonging to Logger.
Multiple paths can be excluded:
->layer(
'Logger',
'src/Logger/',
excludePath: [
'src/Logger/Factory/',
'src/Logger/Formatter/',
],
)The exclusion only applies to that particular layer. A file may still resolve to another matching path layer, namespace-pattern layer, or the automatically registered Source layer.
This mirrors the existing exclusion support in layerPattern() and makes nested architecture boundaries easier to express without changing the directory structure.
The YAGNI preset can now detect unused named functions.
A new rule:
MustBeUsedFunctionRulechecks whether a function is called or otherwise referenced within the scanned code.
For example:
-function legacy_helper(): string
-{
- return 'unused';
-}The rule understands usages including:
'App\helper';A function that only recursively calls itself still counts as unused.
MustBeUsedFunctionRule supports --fix, removing the unused function automatically. It can also clean up an empty surrounding if (! function_exists(...)) guard and remove the file when only boilerplate remains.
The rule is enabled automatically by:
Preset::YAGNI()As with the other YAGNI rules, only usages inside the scanned paths are known. Functions intended as public extension points for external consumers can be excluded with skipRule() or skip paths.
Custom function rules can opt into function-usage analysis through the new:
Boundwize\StructArmed\Rule\UsedFunctionAwareRuleInterfaceIt extends FunctionRuleInterface and makes the usage state available through:
$functionNode->isReferencedFor example:
final readonly class CustomRule implements UsedFunctionAwareRuleInterface
{
public function appliesTo(FunctionNode $functionNode): bool
{
return $functionNode->isInLayer('Source');
}
public function evaluate(FunctionNode $functionNode): ?RuleViolation
{
if ($functionNode->isReferenced) {
return null;
}
// ...
}
}Usage analysis is opt-in: StructArmed performs the additional work only when at least one active rule implements UsedFunctionAwareRuleInterface.
The PHPUnit extension is now easier to control in CI.
Set:
STRUCTARMED_DISABLED=1 vendor/bin/phpunitStructArmed remains configured in phpunit.xml, but the extension skips architecture analysis for that run.
This is useful when StructArmed already runs as a dedicated CI step.
PHPUnit's own --no-progress now also disables the StructArmed progress bar:
vendor/bin/phpunit --no-progressTo disable only StructArmed's progress output while preserving PHPUnit's progress display:
<extensions>
<bootstrap class="Boundwize\StructArmed\PHPUnit\StructArmedExtension">
<parameter name="progress" value="false"/>
</bootstrap>
</extensions>StructArmed now requires:
"nikic/php-parser": "^5.9"--report=github in #445^5.9 in #448excludePath in Architecture::layer() in #450STRUCTARMED_DISABLED env to disable the PHPUnit extension in #459UsedFunctionAwareRuleInterface and MustBeUsedFunctionRule for YAGNI preset in #462Full Changelog: 0.17.12...0.18.0
Full Changelog: 0.17.12...0.18.0
perf: Merge same layer check into allowed layers loop by @samsonasik in #455
Full Changelog: 0.17.11...0.17.12
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.11...0.17.12
Fix enum protected-to-private fixer producing invalid "final private" members by @samsonasik in #453
Full Changelog: 0.17.10...0.17.11
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.10...0.17.11
fix: Prefer specific layer over equally specific Source layer in NamespaceLayerResolver by @samsonasik in #449
Full Changelog: 0.17.9...0.17.10
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.9...0.17.10
refactor: Merge loadAnalysisNodesWithFileAnalysis into loadAnalysisNodes via $withFileAnalysis flag by @samsonasik in #440
Full Changelog: 0.17.8...0.17.9
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.8...0.17.9
fix: Resolve same-file function calls only against unconditionally declared functions by @samsonasik in #439
Full Changelog: 0.17.7...0.17.8
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.7...0.17.8
fix: Resolve names before PSR-1 file-state analysis, reusing the extractor's AST by @samsonasik in #438
Full Changelog: 0.17.6...0.17.7
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.6...0.17.7
perf: Optimize object-bound anonymous-function detection hot path by @samsonasik in #433
Full Changelog: 0.17.5...0.17.6
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.5...0.17.6
perf: Optimize baseline generation and filtering performance by @samsonasik in #431
Full Changelog: 0.17.4...0.17.5
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.4...0.17.5
chore: Bump nikic/php-parser version to ^5.8 by @samsonasik in #429
Full Changelog: 0.17.3...0.17.4
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.3...0.17.4
refactor: Extract shared nameEndsWith()/nameStartsWith() into NameQueryTrait for ClassNode and FunctionNode by @samsonasik in #424
Full Changelog: 0.17.2...0.17.3
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.2...0.17.3
refactor: Pair each class-like with its analysis instead of keying by spl_object_id() by @samsonasik in #421
Full Changelog: 0.17.1...0.17.2
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.1...0.17.2
perf: Compact FileAnalysis cache scalars into a positional list by @samsonasik in #414
Full Changelog: 0.17.0...0.17.1
Full Changelog: https://github.com/boundwize/structarmed/compare/0.17.0...0.17.1
StructArmed 0.17.0 expands architecture analysis beyond named classes.
StructArmed 0.17.0 expands architecture analysis beyond named classes.
This release introduces dedicated analysis nodes and rule interfaces for:
It also introduces the new PER Coding Style and Code Quality presets, expands the MVC and DDD presets, adds several fixable coding-style rules.
Three new interfaces allow custom rules to target a specific kind of PHP declaration:
Boundwize\StructArmed\Rule\FunctionRuleInterfaceBoundwize\StructArmed\Rule\AnonymousFunctionRuleInterfaceBoundwize\StructArmed\Rule\AnonymousClassRuleInterfaceEach interface uses the same appliesTo() and evaluate() method names as the existing RuleInterface, but receives a node containing information specific to that declaration type.
| Interface | Node | Analyses |
|---|---|---|
FunctionRuleInterface |
FunctionNode |
Named functions |
AnonymousFunctionRuleInterface |
AnonymousFunctionNode |
Closures and arrow functions |
AnonymousClassRuleInterface |
AnonymousClassNode |
Anonymous classes |
These nodes expose information such as their source file, line, layer, dependencies, function calls, superglobal access, language constructs, parameters, return types, complexity, and line count.
Anonymous-function nodes additionally report whether the declaration:
static;$this;Anonymous-class nodes include:
The new MustHaveReturnTypeFunctionRule requires named functions in a configured layer to declare a return type.
It is enabled for the MVC preset's Helper layer.
-function format_price(int $amount)
+function format_price(int $amount): string
{
return number_format($amount);
}This complements the existing method return-type rules: standalone helper functions can now be checked independently from class methods.
The new MustBeStaticAnonymousFunctionRule detects closures and arrow functions that do not access $this but have not been declared static.
-$activeUsers = array_filter($users, function (User $user): bool {
+$activeUsers = array_filter($users, static function (User $user): bool {
return $user->isActive();
});Arrow functions are supported as well:
-$ids = array_map(fn (User $user): int => $user->id, $users);
+$ids = array_map(static fn (User $user): int => $user->id, $users);Closures that read $this, directly or through a nested closure, are skipped because PHP does not allow $this inside a static closure.
This rule supports --fix.
Anonymous classes now have their own AnonymousClassNode representation and rule interface.
Their class members, dependencies, traits, readonly status, and parent hierarchy are collected just like those of named classes. Consequently, methods such as extendsClass() and implementsInterface() work across direct and transitive parents.
The new fixable AnonymousClassMayNotHaveEmptyParenthesesRule implements the PER convention that an anonymous class passing no constructor arguments should omit empty parentheses:
-$handler = new class () implements Handler {
+$handler = new class implements Handler {
public function handle(): void
{
}
};Parentheses containing actual constructor arguments are unaffected.
The new Preset::PER() implements additional rules from the PER Coding Style and includes the existing PSR-12 rules.
Enable it in structarmed.php:
return Architecture::define()
- ->withPresets(Preset::PSR4(), Preset::PSR12());
+ ->withPreset(Preset::PER());In addition to PSR-12, the PER preset checks the following conventions.
enum OrderStatus
{
- case pending_payment;
+ case PendingPayment;
}Enums cannot be extended, so protected methods should be private:
enum OrderStatus
{
- protected function label(): string
+ private function label(): string
{
return $this->name;
}
} enum OrderStatus
{
- protected const DEFAULT_LABEL = 'Unknown';
+ private const DEFAULT_LABEL = 'Unknown';
}-$object = new class () {};
+$object = new class {};The enum visibility and anonymous-class-parentheses rules support --fix.
The PSR-12 preset now includes the fixable MustUseLowercaseKeywordConstantRule.
It requires the PHP keyword constants true, false, and null to use their canonical lowercase spelling:
-$enabled = TRUE;
-$disabled = FALSE;
-$value = NULL;
+$enabled = true;
+$disabled = false;
+$value = null;Only the spelling is changed. For example, a fully qualified \TRUE becomes \true.
The new Preset::CODEQUALITY() provides readability rules that are independent of a particular architecture style or coding standard.
Enable it alongside other presets:
return Architecture::define()
->withPresets(
Preset::DDD(),
+ Preset::CODEQUALITY(),
);Closures and arrow functions that do not use $this must be declared static.
-$names = array_map(fn (User $user) => $user->name, $users);
+$names = array_map(static fn (User $user) => $user->name, $users);Declaring these functions static makes it explicit that they do not capture the enclosing object.
Plain decimal numeric literals of at least 1_000_000 must group their digits using _ separators:
-$maximumUploadSize = 10000000;
+$maximumUploadSize = 10_000_000;Decimal fractions retain their fractional portion:
-$amount = 1000500.75;
+$amount = 1_000_500.75;The default threshold can be customized by replacing the preset rule:
<?php
use Boundwize\StructArmed\Architecture;
use Boundwize\StructArmed\Preset\Preset;
use Boundwize\StructArmed\Preset\Presets\CodeQualityPreset;
use Boundwize\StructArmed\Rule\Rules\File\LargeNumericLiteralMustUseSeparatorRule;
return Architecture::define()
->withPreset(Preset::CODEQUALITY())
->replaceRule(
CodeQualityPreset::LARGE_NUMERIC_LITERALS_MUST_USE_SEPARATOR,
new LargeNumericLiteralMustUseSeparatorRule(minimum: 1_000),
);Both Code Quality rules support --fix.
The new MayNotExtendClassRule prevents classes in a layer from extending a configured class, either directly or through a parent class.
The DDD preset uses it to prevent Domain classes from extending Doctrine's infrastructure-oriented EntityRepository:
namespace App\Domain\Repository;
-use Doctrine\ORM\EntityRepository;
-
-final class OrderRepository extends EntityRepository
+interface OrderRepository
{
}A custom rule can enforce the same boundary for another framework base class:
use Boundwize\StructArmed\Rule\Rules\Class_\MayNotExtendClassRule;
return Architecture::define()
->layer('Domain', 'src/Domain/')
->rule(
'domain.must_not_extend_eloquent_model',
new MayNotExtendClassRule(
layer: 'Domain',
class: 'Illuminate\Database\Eloquent\Model',
),
);For example, the following rule prevents named functions in the Domain layer from reading PHP superglobals:
<?php
namespace App\Architecture\Rules;
use Boundwize\StructArmed\Analyser\FunctionNode;
use Boundwize\StructArmed\Rule\FunctionRuleInterface;
use Boundwize\StructArmed\Rule\RuleViolation;
use function sprintf;
final readonly class FunctionsMustNotAccessSuperglobalsRule implements FunctionRuleInterface
{
public function appliesTo(FunctionNode $functionNode): bool
{
return $functionNode->isInLayer('Domain');
}
public function evaluate(FunctionNode $functionNode): ?RuleViolation
{
if (! $functionNode->accessesSuperglobals()) {
return null;
}
return new RuleViolation(
message: sprintf(
'Function [%s()] must not access superglobals',
$functionNode->functionName,
),
file: $functionNode->file,
line: $functionNode->line,
className: $functionNode->functionName,
layer: $functionNode->layer,
functionName: $functionNode->functionName,
);
}
}Register it like any other rule:
return Architecture::define()
->layer('Domain', 'src/Domain/')
->rule(
'domain.functions_must_not_access_superglobals',
new FunctionsMustNotAccessSuperglobalsRule(),
);Global skip paths, rule-scoped skip() paths, and skipRule() also apply to function, anonymous-function, and anonymous-class rules.
Layer-aware rules now extend AbstractLayerAwareRule instead of implementing LayerAwareRuleInterface.
-use Boundwize\StructArmed\Rule\LayerAwareRuleInterface;
+use Boundwize\StructArmed\Rule\AbstractLayerAwareRule;
-final class DomainDependencyRule implements RuleInterface, LayerAwareRuleInterface
+final class DomainDependencyRule extends AbstractLayerAwareRule implements RuleInterface
{
}The base class provides the class-node map injection and getDependencyNode() lookup used to inspect the layer of another scanned class.
Token-aware fixer visitors similarly use AbstractTokenAwareVisitor instead of TokenAwareVisitorInterface.
Several internal extractor and parallel-worker classes were also renamed from ClassNode* to AnalysisNode* to reflect their expanded support for functions and anonymous classes.
Full Changelog: 0.16.31...0.17.0
Fix: normalise reported composer.json path in PSR-4 rules for consistent violation display on Windows by @samsonasik in #381
Full Changelog: 0.16.30...0.16.31
dx: use 💡 icon in Hint for --fix usage on ConsoleReport by @samsonasik in #377
Full Changelog: 0.16.29...0.16.30
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.29...0.16.30
perf: Remove fflush call from WorkerProgressHandler::advance() method by @samsonasik in #372
Full Changelog: 0.16.28...0.16.29
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.28...0.16.29
perf: Reduce redundant key-scan passes when decoding cached nodes in AnalysisResultCache by @samsonasik in #362
Full Changelog: 0.16.27...0.16.28
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.27...0.16.28
perf: Single-pass source path matching in PhpFileFinder::filesFromScope() by @samsonasik in #361
Full Changelog: 0.16.26...0.16.27
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.26...0.16.27
chore: Clean up no longer used method sourcePathsFor() on Psr4SourcePathsRule by @samsonasik in #357
Full Changelog: 0.16.25...0.16.26
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.25...0.16.26
 ![PHPStan]
Full Changelog: https://github.com/boundwize/structarmed/compare/0.16.24...0.16.25
Full Changelog: 0.16.24...0.16.25
 ![PHPStan]
Full Changelog: 0.16.23...0.16.24
 ![PHPStan]
Full Changelog: 0.16.22...0.16.23