The design principles describe how the scaffold is
built. The rules on this page turn the parts of them that a tool can check into
checks that fail as soon as code breaks them, in the editor, in
composer lint and in CI.
They exist for whoever extends the scaffold next, person or coding agent. A failure does not only say that a rule was broken. It says what to do instead, and links to the principle and to the rule's entry below.
composer lint # includes the PHPStan architecture rules
composer test # includes the architecture test suite
composer test:architecture # only the architecture test suite
composer test:phpstan-rules # only the tests of the PHPStan rules
composer check:autoloader # source declarations through the bundled autoloader alone
composer api:snapshot # regenerate the infrastructure API listing after reviewCI also runs php -n scripts/check-bundled-autoloader.php on PHP 7.4 in a
checkout without vendor/, before installing any dependencies. This loads every
class, interface and trait under src/ directly through the bundled autoloader,
independently of the bootstrap's Composer detection (#10).
Each rule lives at the cheapest level that can see what it checks:
| Level | Mechanism | Where |
|---|---|---|
| Code | PHPStan rules, run with the rest of the static analysis | tests/php/PHPStan/Rule/ |
| Repository and composition root | PHPUnit tests in the architecture suite |
tests/php/Architecture/ |
Every rule has an identifier such as architecture.finalByDefault and one
entry in tests/php/Architecture/RuleManifest.php. The entry ties the
identifier to the principle it enforces, to its section on this page and,
where one applies, to the pattern that meets the need the
rejected code was after.
Every failure has the same three parts:
- What is wrong, and where, naming the class or file.
- What to do instead.
- Why, how and what exactly: the principle, the pattern when there is one, and the rule's section on this page. PHPStan shows this part as the tip under the error.
Change the code so it follows the rule. The message says how, and docs/patterns.md shows the scaffold's way of meeting the need the code was after, with examples that pass the checks.
Never silence an architecture rule with an inline @phpstan-ignore, an
ignoreErrors entry or a baseline. If the rule is wrong for a real case, open
an issue with needs: decision that names the case. Exceptions the maintainer
accepts become configuration under parameters.architecture in
phpstan.neon.dist, where they stay visible and reviewed.
The rules read the plugin's namespace and their allowances from
parameters.architecture in phpstan.neon.dist. A plugin generated from the
scaffold renames the namespaces there together with its own namespace, and
the rules follow.
| Setting | Meaning |
|---|---|
namespace |
The plugin's root namespace. Rules only look at code inside it. |
excludedNamespaces |
Parts of that namespace that are not plugin code, such as the tests. |
Settings that belong to one rule are listed in its section.
The checks of the repository's structure read the PSR-4 roots from
composer.json and the test suites from phpunit.xml.dist. What those files
cannot tell, such as the main plugin file and the view template directories,
RepositoryLayout in tests/php/Architecture/ declares.
- Add an entry to
RuleManifest: identifier, principle and its anchor indocs/design-principles.md, the configuration key, what checks it (checked_by: the PHPStan rule classes, or the test methods of the architecture suite), and fixed phrases of its messages (signatures), which let the suppression check recognize ignores aimed at it. When a section ofdocs/patterns.mdshows how to meet the need the rule protects, name its anchor aspattern, and list the rule under that section's Rules; add a section if the need is new and recurs. - Write the rule in
tests/php/PHPStan/Rule/, using the identifier andRuleManifest::get_explanation()as the tip, or write the check as a test intests/php/Architecture/. - Test a PHPStan rule with PHPStan's
RuleTestCaseagainst fixtures intests/php/PHPStan/Fixture/: one that breaks the rule, with the full message asserted, and one for each case it allows. Fixtures that refer to each other's classes need one class per file, following PSR-4, because PHPStan's test case only finds classes it can autoload. - Register it in
tests/php/PHPStan/rules.neon, and put its settings underparameters.architectureinphpstan.neon.dist. - Add its section below, and link each pattern that lists the rule under
its Fix.
RuleManifestTestfails until the section exists, andRuleRegistrationTestuntil the rule and its patterns lead to each other.
The tree must pass a new rule without a baseline. Fix what it finds, or file the findings as their own issues and land the rule after them.
PHPStan rules build on PHPStan 2 and prefer the classes and methods it tags
@api, which its backward compatibility promise covers. Psalm 5 crashes when
it loads a PHPStan 2 class, and it loads every class a scanned file references.
So tests/php/PHPStan/ stays out of Psalm's scan, and any other file names
PHPStan classes, including the rules, by string rather than with ::class, as
RuleManifest does.
Not everything a principle asks for can be checked mechanically. This table says which rules enforce each principle, and what stays with review.
| Principle | Checked by | Reviewed by hand |
|---|---|---|
| The core idea: complexity that grows linearly | hooksInLifecycleMethods, queryContextNeedsDelay, registrationActionKnown, capabilitiesOnServices, servicesDeclared, compositionRootContracts |
Each service deciding its own lifecycle through capability interfaces |
| 1. Runs on PHP and WordPress alone | noRuntimeDependencies, declarationsFollowPsr4, explicitNullableParameters; bundled autoloader CI check |
Bootstrap Composer detection (#10) |
| 2. Self-contained infrastructure | dependencyDirection (subsystems depend on interfaces) |
Keeping the simple implementations simple |
| 3. Defaults out of the box | newOnlyWhereAllowed (the shape of a poka-yoke default) |
Whether a collaborator has an obvious default |
| 4. SOLID at the top | dependencyDirection |
Single responsibility, open/closed and Liskov substitution |
| 5. One composition root | newOnlyWhereAllowed, noStaticState, pluginFactoryOnlyAtEdges, noServiceLocator, dependencyDirection, capabilitiesOnServices, servicesDeclared, compositionRootContracts |
|
| 6. Final by default | finalByDefault |
Whether a listed base class is designed for extension |
| 7. WordPress anti-patterns | constructorsOnlyAssign, noHooksInConstructor, hooksInLifecycleMethods, noContextChecksInRegister, queryContextNeedsDelay, registrationActionKnown, noSideEffectsOnInclude, noStaticState, pluginFactoryOnlyAtEdges, newOnlyWhereAllowed, noGlobalState, outputOnlyThroughViews |
God classes |
| 8. Types name concepts | namesWithoutTypeKind; PHPStan at level max and Psalm at level 2, for consistency |
Whether a value deserves a type of its own; whether implementation names describe their distinguishing behaviour |
| 9. Never trust what WordPress hands over | noGlobalState (request input only in adapters), rawIsEscaped, PHPCS (WordPress Coding Standards) for escaping output |
Validating input at the boundary |
| 10. Errors are exceptions | noWordPressErrorMechanisms, noFalseOnFailure, throwOnlyPluginExceptions, exceptionShape, exceptionsThroughNamedConstructors, exceptionsKeepCause |
Graceful degradation at the boundary: views (#27, #30), other callbacks and lifecycle steps (#143); the scoped lifecycle events propagate by ruling (#34) |
| 11. Lifecycle steps are idempotent | compositionRootContracts |
Plugin registration orchestration (#26); effects outside Brain Monkey |
| 12. Extension points at a hook | noSideEffectsOnInclude, noHooksInConstructor, bootstrapContract |
|
| 13. One plugin, to arbitrary complexity | prefixedNames, serviceIdsPrefixed |
The value of VIEW_OVERRIDE_DIRECTORY; service IDs added by runtime filters |
| 14. The code teaches | samplesAreTested, testsAreDiscovered, citationsResolve, infrastructureApiSnapshot |
Whether comments explain why and cited lines still support the prose |
| Hard rules | strictTypes, noSuppression, suppressionsAreNamed, testsAreDiscovered, gatesAtStrength, everyPathAnalysed, infrastructureApiSnapshot |
API compatibility and maintainer rulings on breaking changes |
Each of these mistakes fails composer lint or composer test with a message
that names the fix. The fixtures and tests listed prove it.
| Mistake | Fails with | Proven by |
|---|---|---|
| An inline suppression hides every error on its line or in its file | suppressionsAreNamed |
SuppressionTest::test_it_reports_each_unnamed_suppression_with_the_full_message |
| An infrastructure signature changed without updating its reviewed snapshot | infrastructureApiSnapshot |
InfrastructureApiSnapshotTest::test_it_reports_a_difference_with_the_diff_and_regeneration_command |
| A service constructor reading an option or branching | constructorsOnlyAssign |
tests/php/PHPStan/Fixture/ConstructorsOnlyAssign/CallService.php, BranchService.php |
| A hook added in a constructor | noHooksInConstructor |
tests/php/PHPStan/Fixture/Hooks/Feature/BadService.php |
| A bootstrap applying a filter before other plugins can hook in | bootstrapContract |
tests/php/Fixture/BootstrapContract/filters-too-early.php, BootstrapContractTest::test_it_reports_a_filter_applied_at_include_time_with_the_fix |
new of a service inside another service |
newOnlyWhereAllowed |
tests/php/PHPStan/Fixture/Creation/Consumer.php |
A class that is not final |
finalByDefault |
tests/php/PHPStan/Fixture/FinalByDefault/classes.php |
| A bare SPL exception thrown | throwOnlyPluginExceptions |
tests/php/PHPStan/Fixture/Errors/Service.php |
| A public WordPress name without the plugin's prefix, or an overlong post type/taxonomy name | prefixedNames |
tests/php/PHPStan/Fixture/Names/Service.php, Registrations.php, NameLengths.php |
| A declared service ID without the composition root's configured prefix | serviceIdsPrefixed |
CompositionRootContractTest::test_it_reports_an_unprefixed_service_id_with_the_fix |
| Sample-plugin service IDs left in a root with a different prefix | serviceIdsPrefixed |
CompositionRootContractTest::test_it_rejects_sample_service_ids_in_a_root_with_a_different_prefix |
| An empty service prefix that leaves every declared ID unprefixed | serviceIdsPrefixed |
CompositionRootContractTest::test_it_reports_service_ids_when_the_service_prefix_is_empty |
| A sample class or production view without a test | samplesAreTested |
SamplesAreTestedTest::test_it_reports_an_untested_subsystem_class_with_the_fix, SamplesAreTestedTest::test_it_reports_an_untested_view_with_the_fix |
| A test file outside a test suite | testsAreDiscovered |
RepositoryStructureTest::test_it_reports_tests_phpunit_never_runs |
| A service calling the plugin factory as a static service locator | pluginFactoryOnlyAtEdges |
tests/php/PHPStan/Fixture/PluginFactoryOnlyAtEdges/Service.php |
| A documentation citation naming a missing file, an out-of-bounds line or a reversed range | citationsResolve |
RepositoryStructureTest::test_it_reports_broken_documentation_citations_with_full_messages |
| A service pulling a collaborator or request input from globals | noGlobalState |
tests/php/PHPStan/Fixture/NoGlobalState/Service.php |
| HTML or a string printed directly by a service | outputOnlyThroughViews |
tests/php/PHPStan/Fixture/OutputOnlyThroughViews/Service.php |
| A raw view value printed without escaping | rawIsEscaped |
tests/php/PHPStan/Fixture/RawEscaping/views/unescaped.php |
| A subsystem receiving the container or configuring the injector | noServiceLocator |
tests/php/PHPStan/Fixture/NoServiceLocator/Feature/Constructor.php, Reconfigures.php |
| A sample service depending on a concrete infrastructure class | dependencyDirection |
tests/php/PHPStan/Fixture/Layers/Feature/Service.php |
| A lifecycle capability on a class that is not a service | capabilitiesOnServices |
tests/php/PHPStan/Fixture/Capabilities/RegisterableOnly.php |
| A delayed service with nothing to register | capabilitiesOnServices |
tests/php/PHPStan/Fixture/Capabilities/DelayedService.php |
| A subsystem service missing from the composition root | servicesDeclared |
ServicesDeclaredTest::test_it_reports_an_undeclared_subsystem_service_with_the_fix |
| A service the composition root cannot build | compositionRootContracts |
tests/php/Fixture/CompositionRoot/BrokenPlugin.php |
| A delayed service waiting for a misspelled action | registrationActionKnown |
tests/php/Fixture/CompositionRoot/TypoActionPlugin.php |
Principle: 13. One plugin, to arbitrary complexity.
Checks: every key of the composition root's get_service_classes() starts
with that root's configured SERVICE_PREFIX. An empty SERVICE_PREFIX leaves
every declared ID unprefixed, so each is reported. Failures name the ID, root
and configured prefix, and explain how to fix the declaration.
Allows: IDs beginning with the root's own nonempty prefix, including in
generated plugins with different prefixes. Only the recorded declaration keys
are inspected: this check does not resolve callable declarations, construct
lazy services, reread configuration or rerun runtime callbacks. The existing
composition-root contract still resolves and builds services for its other
checks. Runtime filter output, such as IDs added via the services filter,
is outside this check's scope.
Configuration: RepositoryLayout::COMPOSITION_ROOT selects the root through
the existing composition-root contract test. SERVICE_PREFIX is read from
that root by reflection, including protected constants, rather than copied
from the sample plugin.
Fix: set a nonempty SERVICE_PREFIX in the composition root and build every
declared ID from it in get_service_classes(). See
I need a name in a space WordPress shares.
Principle: Hard rule: infrastructure changes are API changes.
Checks: reflection of the infrastructure matches the committed listing in
tests/php/Architecture/infrastructure-api.txt. Every type has a declaration
line (including empty marker interfaces). Interfaces, traits, abstract classes
and non-final classes contribute public and protected constants, properties
and methods; final classes contribute public methods. Inherited userland
members count too. Each line names its owning API type relative to the plugin's
root namespace, and the lines are sorted. Signatures include visibility,
static/abstract/final method modifiers, native types, reference returns and
parameters, variadics and evaluated default values. Untyped declarations stay
untyped, and uninitialized typed properties have no default.
Allows: private members and final-class constants and properties can change
without updating the snapshot. PHP-owned inherited methods are excluded: their
signatures belong to the installed PHP version, not to this repository.
Every type also lists the interfaces it implements or extends, inherited ones
included, so dropping one is visible. Interfaces that PHP provides itself are
left out, so PHP 8's implicit Stringable does not change the listing. Constants used as defaults are rendered as values,
strings and arrays stay on one line, and repository paths become <root>/....
Exceptions and the composition root are outside this check.
Configuration: parameters.architecture.namespace and
parameters.architecture.dependencyDirection.infrastructure in
phpstan.neon.dist, with source discovery from RepositoryLayout. Renaming
the configured root namespace and the source together preserves the snapshot.
Fix: review the printed diff, then run composer api:snapshot and include
the updated listing in the PR. A snapshot diff that removes or changes existing
API needs the breaking label and a maintainer ruling; a diff that only adds
API does not. Regeneration acknowledges a change, not its compatibility.
Principle: 14. The code teaches.
Checks: repository-relative file citations in inline code spans in
AGENTS.md, README.md and every Markdown document below docs/. A citation
names a path with a recognizable file extension followed by a colon and a
line number or line range. The file must exist, line numbers start at 1,
neither endpoint may exceed the file's line count, and ranges cannot run
backwards. Failure messages name the document, citation and problem.
Allows: ordinary prose, fenced code blocks, URLs, host-and-port pairs, static references, absolute paths and parent-relative paths. Single- and multiple-backtick inline spans, including multiline spans, are checked. This checks file and line existence; whether the cited lines still support the prose stays with review. Citations in issue bodies are outside its scope.
Configuration: RepositoryLayout::DOCUMENTATION lists individual Markdown
files and directories to search recursively. The check uses repository paths
without depending on the plugin's namespace or prefixes. Recognized file
extensions are php, md, txt, json, lock, neon, yml, yaml, xml,
dist, ini, sh, js, ts, css, html and svg.
Fix: correct the path or line numbers to cite existing lines in the repository. Check that those lines also support the surrounding explanation.
Principle: 6. Final by default.
Checks: every concrete class in the plugin's namespace is final.
Allows: abstract classes, interfaces, traits and anonymous classes, and the
classes listed as designed base classes. A @final tag in a docblock does not
count: the class can still be extended.
Configuration: finalByDefault.baseClasses lists the classes designed to be
extended. The scaffold lists SimpleView, the base of TemplatedView.
Fix: declare the class final, and vary its behaviour through interfaces
and injected collaborators. Add it to baseClasses only when it is designed
for extension from the start.
Pattern: I need to start simple and add implementations later.
Principle: 8. Types name concepts, not just data: a name survives promotion from a concrete class to an interface.
Checks: class, interface and trait names in the plugin's namespace do not
start with I followed by an uppercase letter, Abstract or Base, and do
not end in Interface, Trait, Abstract, Impl, Implementation, Class
or Exception. Messages name the type, suggest its name without the marker
words, and explain why the name must survive promotion.
Allows: anonymous classes, names outside the plugin's namespace, names in
excludedNamespaces, and reviewed allowances. Only the configured exception
marker interface may keep the Exception suffix; other exception interfaces
and concrete exceptions are checked. Roles such as FooFactory, capabilities
such as Registerable and HasDependencies, distinguishing names such as
SimpleFoo, and Image (an I followed by lowercase) pass.
Configuration: namesWithoutTypeKind.allowed lists fully qualified type
names accepted after review, empty by default. The exception marker comes
from exceptions.marker. Both are compared without regard to case and with
leading or trailing namespace separators removed. Marker words themselves
are matched case-sensitively.
Fix: remove the kind marker and name the concept. Name implementations by
what distinguishes them (Simple…, WordPress…, Cached…), never …Impl,
Default… or Base…. The choice of a distinguishing name stays with review.
See I need to start simple and add implementations later.
Principle: 5. One composition root builds the object graph, which allows static state only in the plugin factory, and the anti-pattern table in principle 7.
Checks: no static properties and no static variables in the plugin's
namespace.
Allows: static methods and class constants, which hold no state, and the methods and properties listed in the configuration. Anonymous classes declared in the plugin's namespace are checked too.
Configuration: noStaticState.allowed lists methods as Class::method and
properties as Class::$property. As in PHP, class and method names match
regardless of case, property names only exactly. The scaffold lists
BasicScaffoldPluginFactory::create, which keeps the one plugin instance that
WordPress reaches from outside the object graph.
Fix: keep the value on an instance, and let the injector share that
instance with share() when more than one object needs it. A cache belongs on
the object that computes it.
Patterns: I need a singleton, I need a service locator, I need to reach the plugin from a static WordPress callback.
Principles: 5. One composition root builds the object graph and 7. Show the alternative to WordPress anti-patterns.
Checks: no direct static call to a configured plugin factory from the
plugin's namespace or production views. Inside the object graph, the factory
would be a static service locator. Calls through self, static and parent
are resolved to their class too.
Allows: the main plugin file declared by RepositoryLayout::BOOTSTRAP,
and calls directly inside a listed bridge method. Other methods of the same
class and closures inside a bridge are still checked. Tests and unrelated
namespaces are outside the rule's scope; unrelated static calls are untouched.
Calls through a class expression chosen at runtime are not checked.
Configuration: pluginFactoryOnlyAtEdges.factories lists factory classes;
the scaffold lists MWPD\BasicScaffold\BasicScaffoldPluginFactory.
pluginFactoryOnlyAtEdges.bridges lists reviewed methods as Class::method;
the scaffold lists BasicScaffoldUninstallHook::uninstall, which WordPress
stores as the uninstall callback. Class and method names match without regard to case
or a leading backslash. dependencyDirection.views supplies the production
view directories, as for noGlobalState.
Fix: receive what is needed through the constructor. For on-demand creation, receive a factory or the injector. A static callable that WordPress invokes belongs in a listed bridge: get the graph through the plugin factory and delegate immediately to instance services, nothing else. The bridge holds no state or feature logic; reviewing that contract remains a human check. See I need to reach the plugin from a static WordPress callback and I need a service locator, and the uninstall bridge in I need to clean up when the plugin is uninstalled. Themes and other plugins get no bridge; they use the plugin's hooks, as I need a public API for themes or other plugins shows.
Principles: 7. Show the alternative to WordPress anti-patterns and 9. Never trust what WordPress hands over.
Checks: no global statements or $GLOBALS access in the plugin's
namespace (excluding excludedNamespaces) or production view directories.
This includes the namespaced bootstrap, file scope, functions, closures and
anonymous classes. The request superglobals $_GET, $_POST, $_REQUEST,
$_COOKIE, $_SERVER, $_FILES and $_ENV are only allowed inside listed
input adapter classes. Reads and writes both count as access.
Allows: constructor-injected values and calls to WordPress functions such
as get_post(), even when those functions read globals internally. Other
superglobals, such as $_SESSION, are outside this rule's scope. Listing an
adapter never permits global or $GLOBALS.
Configuration: noGlobalState.inputAdapters lists classes that sanitize
and normalize request input into internal types; the scaffold needs none.
Class names match without regard to case or a leading backslash; subclasses
need their own entry. Closures inside a listed class may read input; functions
and closures in templates without a class are not adapters.
dependencyDirection.views supplies the production view directories.
Fix: receive the value through the constructor. Configure a delegation in
the composition root for collaborators such as $wpdb or WP_Query. For
state that changes while the request runs, such as the post being rendered,
inject an interface and ask it at call time, as SampleLoopService asks
MainLoop (src/SampleSubsystem/MainLoop.php). Read request input in a listed
adapter and pass its normalized internal type to the service. Sanitization
itself remains with WordPress Coding Standards' ValidatedSanitizedInput
sniff and review. See I need WordPress state, such as the current post.
Principle: 10. Errors are exceptions.
Checks: inside the plugin's namespace, no calls to error_log(),
trigger_error(), user_error() or _doing_it_wrong(), no new WP_Error(),
and no WP_Error in a parameter, return or property type, native or in a
docblock, of a method, function, closure or arrow function. A subclass of
WP_Error counts as a WP_Error.
Allows: inspecting what WordPress returns with is_wp_error() or
instanceof WP_Error, which is how a WP_Error becomes an exception where the
call is made. Classes listed as boundary adapters may create and return
WP_Error objects, for WordPress APIs that expect one, such as a REST
callback.
Configuration: noWordPressErrorMechanisms.boundaryAdapters lists the
classes that hand a WP_Error to WordPress. The scaffold has none yet.
Fix: throw a dedicated exception. The code that hands control back to WordPress catches it and decides what the user sees.
Pattern: I need to report a failure.
Principle: 10. Errors are exceptions.
Checks: inside the plugin's namespace, no method, function, closure or arrow
function declares a return type that unions literal false with another type,
such as string|false. Native unions and @return, @phpstan-return and
@psalm-return tags are checked.
Allows: plain bool, false alone, nullable returns and inferred return
types. A union nested inside a returned value, such as array<string|false>,
is allowed. Whether false or null signals a failure in other cases stays
with review. The rule does not inspect what WordPress functions return.
Configuration: none beyond the plugin's namespace.
Fix: return the value and throw a dedicated exception on failure. Turn a
false returned by a WordPress function into an exception where the call is
made.
Pattern: I need to report a failure.
Principle: 10. Errors are exceptions.
Checks: everything the plugin throws implements its marker interface,
BasicScaffoldException. The rule checks two places: every exception the
plugin creates with new, and every throw of anything but a variable.
Allows: throwing a variable, such as passing on what a catch block
caught. A variable holds either a caught exception or one the plugin created,
and creating one is checked.
Configuration: exceptions.marker and exceptions.namespace name the
marker interface and the namespace the exceptions live in.
Fix: add an exception for the failure to src/Exception/, shaped as
architecture.exceptionShape describes, and throw that.
Pattern: I need to report a failure.
Principle: 10. Errors are exceptions.
Checks: every class in the plugin's namespace that implements the marker
interface lives in the exception namespace, extends the SPL exception that
matches its category, and has a named constructor: a public static method that
returns self, declared in the class, a parent or a trait. Everything in the
exception namespace implements the marker interface.
Allows: interfaces that extend the marker interface, abstract exceptions without a named constructor, and code listed as not being an exception.
Configuration: exceptions.notExceptions lists the code in the exception
namespace that is not an exception. The scaffold lists the Stringify trait.
Whether exceptions are final is checked by architecture.finalByDefault.
Fix: what the message says: extend InvalidArgumentException for invalid
input or configuration and RuntimeException for a failure while running, add
a named constructor that states the cause, or move the class.
Pattern: I need to report a failure.
Principle: 10. Errors are exceptions.
Checks: new of one of the plugin's exceptions only happens inside that
exception's own static methods.
Allows: new self( … ) in a named constructor.
Configuration: exceptions.marker.
Fix: call the named constructor the message lists, or add one that states the new cause, so the same failure always reads the same.
Pattern: I need to report a failure.
Principle: 10. Errors are exceptions.
Checks: inside a catch in the plugin's namespace, a throw of a new
exception through new or a static named constructor passes the caught
variable directly as an argument. An empty catch, including one containing
only comments, also fails. Nested catches are checked against their own
caught variable; functions, closures and classes declared inside a catch are
separate scopes.
Allows: bare rethrows (throw $caught;), translations that pass the caught
variable, and empty catches in listed methods. The check does not follow
variable aliases or inspect how a constructor uses its arguments.
Configuration: exceptionsKeepCause.emptyCatches lists reviewed recoveries
as Class::method, with a reason beside each entry. Class and method names
match regardless of case and allow a leading backslash. An allowance does
not extend to closures inside the method and does not permit losing a cause
when throwing. The scaffold needs no empty catches.
Fix: pass the caught exception to the constructor or named constructor as its previous cause, or rethrow it. Handle the failure in an empty catch; list the method only when doing nothing is an intentional, reviewed recovery. See I need to report a failure.
Principle: 7. Show the alternative to WordPress anti-patterns: HTML belongs in views, rather than in business logic.
Checks: in the plugin's namespace, every expression output by echo,
print, printf() or vprintf() is a direct method call on an object
PHPStan knows is a Renderable or View. Each argument of a multi-argument
echo or formatting call is checked; a rendered view never exempts its
siblings. Inline HTML in namespaced PHP files also fails. String literals,
string variables (even a saved rendering result), concatenations and calls
on unrelated objects with a render() method fail.
Allows: calls such as echo $view->render(),
echo $factory->create( 'views/notice' )->render() and
echo $view->render_partial( 'views/partial' ). Production templates,
code outside the plugin's namespace, excludedNamespaces and explicitly
listed classes are exempt. WordPress output functions such as
wp_send_json() are outside this rule's scope.
Configuration: outputOnlyThroughViews.allowed lists named classes
allowed to output directly; the scaffold needs none. Names match without
regard to case or a leading backslash; subclasses need their own entry.
The rendering interfaces' namespace comes from
dependencyDirection.infrastructure, and production template directories
from dependencyDirection.views.
Fix: render a view from an injected ViewFactory and echo its result.
Put markup and formatting in the template. Escaping inside templates is
checked separately by architecture.rawIsEscaped and PHPCS. The sample's
PHPCS suppression is still needed because PHPCS does not recognize the
rendering method as automatically escaped.
Patterns: I need to print output, I need to see why a service did not run.
Principle: 9. Never trust what WordPress hands over.
Checks: expressions printed with echo, <?= or print in production
view directories escape every $this->raw( … ) occurrence and every use of a
variable directly assigned from that call, including its properties and array
items. Each diagnostic names the template file, output line and escaping
function family.
Allows: property reads such as $this->plugin, which the view escapes
already, and raw values enclosed in a configured escaping function's argument.
Concatenation and nesting inside that argument pass, for example
esc_html( 'Title: ' . strtoupper( $this->raw( 'title' ) ) ). Escaping one
concatenation fragment does not escape its siblings. Unlisted functions such
as strtoupper() alone do not count as escaping.
The check follows only direct assignments from raw() in the template, not
copies, helper return values, closure captures or interprocedural data flow.
Once directly assigned from raw(), a variable needs escaping for the remainder of the
template; the check conservatively does not prove that later assignments or
branches make it safe. Nested function and class bodies are checked in their
own scope, so their local assignments do not affect the enclosing template.
Configuration: dependencyDirection.views supplies the same production
view directories as the dependency rule. rawIsEscaped.escapingFunctions
lists the accepted functions, matched without regard to case or a leading
backslash. Defaults are esc_html, esc_attr, esc_url, esc_js,
esc_textarea, esc_xml, wp_kses, wp_kses_post, wp_kses_data, absint
and intval.
Fix: wrap each raw value, or the expression containing it, in the listed function appropriate to its output context. The check enforces explicit escaping; choosing the right context still needs review. See I need to print output.
Principle: the hard rule that every PHP class
file declares strict_types=1.
Checks: the main plugin file and every file below the PSR-4 roots of
composer.json that declares a class, interface or trait declare
strict_types=1. View templates declare no class, interface, trait or
function, not even conditionally.
Allows: view templates without strict_types, since they are templates
and not class files.
Configuration: RepositoryLayout in tests/php/Architecture/ names the
main file and the view template directories.
Fix: add declare( strict_types=1 ); after the file header, or move a
declaration out of a template into its own class file.
Principle: 1. Runs on PHP and WordPress alone.
Checks: typed parameters with a null default in production class
directories declare their type explicitly nullable. The architecture test
reads the syntax tree, so it also catches PHP 8.4 deprecations on PHP 7.4.
Allows: untyped parameters and explicitly nullable types.
Configuration: the production directories in RepositoryLayout.
Fix: add ? before the parameter type, keeping its null default.
Principle: 1. Runs on PHP and WordPress alone, whose bundled autoloader finds classes the same way Composer does.
Checks: every PHP file below a PSR-4 root of composer.json declares
exactly one class, interface or trait, and its name matches the file's path
exactly, including case.
Allows: anonymous classes, view templates, and the fixtures of the architecture rules, which break rules on purpose.
Configuration: the autoload and autoload-dev sections of
composer.json, and the rule fixture directories in RepositoryLayout.
Fix: give each class, interface or trait its own file, named after it, in the directory its namespace points to.
Principle: 7. Show the alternative to WordPress anti-patterns: only the main plugin file has side effects.
Checks: files in the production directories contain nothing at their top
level but declare directives, namespace, use and class, interface or
trait declarations. Function declarations, function calls, define(),
includes, the body of a declare block and output outside the PHP tags, even
whitespace after a closing ?>, all count as side effects.
Allows: anything inside a class.
Configuration: the production directories in RepositoryLayout.
Fix: move the code into a service method that register() hooks in at
the right time, or into the main plugin file.
Pattern: I need to run code when the plugin file loads.
Principle: 12. Extension points run at a hook, never at include time.
Checks: including the main plugin file in a separate PHP process under
Brain Monkey makes exactly three hook API calls: one add_action() for
plugins_loaded, one register_activation_hook() and one
register_deactivation_hook(). Each registration must have a callable
callback; activation and deactivation must name the included bootstrap.
Callbacks are recorded without being run.
Every other recorded hook API call fails, including add_filter(), removals,
hook queries, register_uninstall_hook(), do_action() and apply_filters().
Rejecting register_uninstall_hook() is deliberate: WordPress stores the
callback in the database, so the plugin registers it on activation. At include
time it would write on every request, and would add the entry back while
WordPress is uninstalling the plugin.
The reference-array and deprecated variants of actions and filters are
recorded too. Duplicate registrations fail even when they would leave the
same final hook state. Missing registrations fail with the required wiring.
Allows: registering the autoloader and building the composition root, provided they make no additional hook API calls. This checks hook calls, not arbitrary PHP side effects or whether registered callbacks do the right work when WordPress later runs them.
Configuration: RepositoryLayout::BOOTSTRAP names the main plugin file.
BootstrapContract also accepts a fixture bootstrap path. No plugin namespace
or hook prefix is hard-coded in the checker, so it follows generated plugins
after renaming. Intentional violations live in
tests/php/Fixture/BootstrapContract, listed in RepositoryLayout::RULE_FIXTURES.
Fix: move the named call into a service's register() or into registration
at plugins_loaded, when other plugins have had a chance to hook in. Keep
exactly one registration for each of the three entry hooks in the bootstrap.
Patterns: I need to run code when the plugin file loads, I need to clean up when the plugin is uninstalled.
Principle: 1. Runs on PHP and WordPress alone.
Checks: composer.json requires nothing but PHP, and
composer-dependency-analyser finds no package used by the code that runs in
production: the main plugin file, src/ and views/. That covers packages in
require-dev and packages only installed because another package needs them.
Allows: the tests use any package.
Configuration: the production paths in RepositoryLayout, which
composer-dependency-analyser.php in the plugin root hands to the analyser
through RuntimeDependencyConfiguration.
Fix: move the package to require-dev and the code that needs it into the
tests, or bundle what the plugin needs into src/.
Principle: the hard rule not to weaken the gates: a test PHPUnit never runs never fails.
Checks: every file ending in Test.php below tests/ lies in a directory
a suite in phpunit.xml.dist discovers, and every concrete PHPUnit test case
lives in such a file.
Allows: abstract base test cases anywhere.
Configuration: the test suites in phpunit.xml.dist, and the tests
directory in RepositoryLayout.
Fix: move the test into a suite directory and name its file after the
class with a Test.php suffix, or add a suite for its directory.
Principle: 14. The code teaches: samples are copied into generated plugins, so they must have tests.
Checks: every concrete class in a feature subsystem is referenced by
::class or a fully qualified @covers annotation in a file discovered by
the unit or integration suite. Class constants follow PHP's namespace and
import rules, including aliases and grouped imports; @covers Class::method
also references its class. Every production PHP view template is named in
such a test by its path relative to the repository, with or without .php,
for example views/test-backend-service. A test that renders through a service
can name the template in its docblock.
Allows: abstract classes, interfaces, traits, classes directly in the plugin's root namespace, infrastructure, exceptions, excluded namespaces and configured composition-root classes. Test templates are outside the check. References in other suites, fixtures, excluded paths or files without the suite's configured suffix do not count. This checks references, not coverage percentages, mutation testing or whether assertions are sufficient.
Configuration: production classes and view directories come from
RepositoryLayout; suite names, directories, suffixes and exclusions come
from phpunit.xml.dist. The plugin namespace, excludedNamespaces,
dependencyDirection.infrastructure, dependencyDirection.compositionRoot
and exceptions.namespace come from parameters.architecture in
phpstan.neon.dist, so generated plugins keep the check after renaming.
Fix: add a unit or integration test that references the class with
::class or @covers, or names the view path and exercises its output.
Principle: the hard rule not to weaken the gates.
Checks: PHPStan stays at level: max without baseline includes; Psalm's
errorLevel is at most 2 and has no errorBaseline attribute; PHPCS references
both WordPress and PHPCompatibility with testVersion set to 7.4-;
phpunit.xml.dist declares the unit, integration, architecture and
phpstan-rules suites. Missing, unreadable or malformed configurations fail
with guidance to restore them. Local PHPStan includes are checked too, and an
include whose filename contains baseline is rejected even if it is missing.
Included files containing PHPStan's generated counted, path-specific ignores
are recognized as baselines even under another filename.
Allows: stronger Psalm levels, additional PHPUnit suites and ordinary
PHPStan extension includes. Installed packages' configurations are not checked.
Existing PHPStan ignoreErrors entries and Psalm issueHandlers are outside
this rule's scope, as are inline suppressions.
everyPathAnalysed checks which paths each tool analyses.
Configuration: the expected levels, standards, compatibility version and
suite names are constants at the top of GatesAtStrengthChecks in
tests/php/Architecture/. A deliberate change to a value is a one-line diff
there for review.
Fix: fix the code instead of weakening the gate; restore the required
configuration. A deliberate change to the policy needs a maintainer ruling
on an issue with needs: decision before changing the expectation.
Principle: the hard rule not to weaken the gates.
Checks: PHPStan, PHPCS and Psalm each include the bootstrap, every production
class and view directory, and the tests directory declared by RepositoryLayout.
An included ancestor covers a required root. Exclusions must not remove a required
root or hide code below it without a reviewed allowance. PHPStan's excludePaths
list and analyse/analyseAndScan map forms are checked, as are Psalm's
projectFiles/ignoreFiles and PHPCS's global exclude-pattern entries.
Missing, unreadable and malformed configurations fail with guidance to restore them.
Allows: exclusions within RepositoryLayout::RULE_FIXTURES, which deliberately
break rules, and the existing documented per-gate exceptions: PHPStan's broken
view fixture; Psalm's broken view fixture and tests/php/PHPStan directory.
Exclusions outside required roots are harmless. PHPCS patterns inside a rule
only affect that sniff and are outside this check's scope. Which rules the gates
run is checked by gatesAtStrength.
Configuration: RepositoryLayout declares BOOTSTRAP, PRODUCTION,
PRODUCTION_VIEWS, TESTS and RULE_FIXTURES. Included roots and exclusions
come from phpstan.neon.dist, phpcs.xml.dist and psalm.xml. The per-gate
allowance constants at the top of EveryPathAnalysedChecks in
tests/php/Architecture/ keep exceptions reviewable; a new entry needs a
documented reason in its gate's configuration.
Fix: add the missing path to the named configuration's included roots or
remove the exclusion it reports. Fix the code instead of hiding it from a gate.
A deliberate policy change needs a maintainer ruling on an issue with
needs: decision before changing an allowance.
Principle: 4. SOLID at the top, WordPress at the edges, whose dependency inversion this keeps, and 5. One composition root builds the object graph.
Checks: which layer of the plugin a class, interface or trait may depend
on, counting every class it mentions: in its file's imports, in code, in
native types and in any documentation tag, such as @var, @throws or
@method:
| A class in | may depend on |
|---|---|
the exceptions (src/Exception/) |
other exceptions |
the infrastructure (src/Infrastructure/) |
the infrastructure and the exceptions |
a feature subsystem (any other top-level namespace, such as src/SampleSubsystem/) |
the infrastructure's interfaces (and traits that only fulfil them), its value objects, the exceptions and the subsystems |
| the composition root | everything |
| any other class directly in the root namespace | the infrastructure's interfaces and the exceptions |
a view template (views/) |
everything but the tests |
Nothing but the tests depends on the tests, not even the composition root. Classes from PHP or WordPress are always fine.
Allows: a subsystem depending on another subsystem; there is no case yet to
decide otherwise. A subsystem class may also use a trait of the infrastructure
whose methods all belong to infrastructure interfaces the class implements,
such as DefaultRegistrationPriority for Delayed: the trait only fulfils a
contract the class already depends on, and is not an object the composition
root could bind instead. A trait that brings any other method is reported.
A subsystem may also name the infrastructure's value objects, the classes
listed in newOnlyWhereAllowed.valueObjects, such as the Style a service
declares in get_assets(): a value is not a collaborator the composition root
could bind instead, which is what the interfaces are for.
Configuration: dependencyDirection.infrastructure names the
infrastructure's namespace, and dependencyDirection.compositionRoot lists the
classes of the composition root: BasicScaffoldPlugin,
BasicScaffoldPluginFactory and the uninstall bridge
BasicScaffoldUninstallHook, an edge like the main file. The value objects come from
newOnlyWhereAllowed.valueObjects. dependencyDirection.views lists the
directories of the view templates that run in production. The exceptions' namespace comes from
exceptions.namespace, the tests' from excludedNamespaces.
Fix: depend on the interface the message names and bind the implementation in the composition root, or receive what you need through the constructor. In the infrastructure, add an interface the other class implements.
Patterns: I need to create objects on demand, I need to choose an implementation at runtime, I need to add a feature.
Principle: 5. One composition root builds the object graph.
Checks: feature subsystems never depend on the configured service container,
including imports, native types, code references and documentation tags. The
positions, attribution to classes and deduplication are shared with
architecture.dependencyDirection: each source/container pair is reported at
its first mention. Calls on a value typed as the configured injector, including
implementations and nullable or union types, must use an allowed method.
Runtime method names are checked against their possible constant strings; an
unknown name is reported because it cannot be proved to use only allowed methods.
Allows: receiving Injector and calling make() for on-demand creation.
Unrelated objects may have methods named bind() or share(). Infrastructure,
exceptions, configured composition-root classes, classes directly in the root
namespace, excluded test namespaces and production view templates are outside
this rule's scope. Feature subsystems are the other namespaces below the plugin
root, exactly as defined by dependencyDirection.
Configuration: noServiceLocator.container defaults to
MWPD\BasicScaffold\Infrastructure\ServiceContainer, noServiceLocator.injector
to MWPD\BasicScaffold\Infrastructure\Injector, and
noServiceLocator.allowedInjectorMethods to [make]. Method names are matched
without regard to case, and configured class names without regard to case or a
leading backslash. Layer boundaries reuse namespace, excludedNamespaces,
exceptions.namespace and dependencyDirection settings.
Fix: receive a known collaborator through the constructor. For objects
created later or per use, receive a typed factory or the injector and call
make(). Configure bindings, sharing and delegations in the composition root.
For a choice by a runtime value, inject a typed factory or registry for that
concept.
Patterns: I need a service locator, I need to create objects on demand, I need to choose an implementation at runtime.
Principle: 5. One composition root builds the object graph.
Checks: every new in the plugin's namespace, by default. A collaborator,
whether a service of the plugin or a WordPress class such as WP_Query, comes
from the injector, not from new in the class that uses it. So do
anonymous classes and objects of a class chosen at runtime.
Allows:
- anything inside a factory: a class named
…Factory, a class implementing an interface named…Factory, or a class implementing one of the configured factory interfaces; - a poka-yoke default,
$this->property = $parameter ?? new Default()in a constructor, when the parameter is nullable and typed to an interface the default implements; the default may be an anonymous class; - value objects in the configured list, and anything throwable; how exceptions
are created is up to
architecture.throwOnlyPluginExceptionsandarchitecture.exceptionsThroughNamedConstructors.
A class chosen at runtime, new $class(), is allowed when PHPStan can prove it
is a value object or throwable.
Configuration: newOnlyWhereAllowed.factories lists the factory
interfaces: the scaffold lists Injector and Instantiator.
newOnlyWhereAllowed.valueObjects lists the value objects: the scaffold lists
LazilyInstantiatedService, ViewLocations, ViewConfiguration, the
lifecycle values in Infrastructure\Lifecycle (IDs, scope, contexts and
selections), RegistrationRecord, ReadOnlyRegistrationReport and PHP's DateTimeImmutable,
DateInterval, ArrayIterator and SplObjectStorage.
Fix: receive the object through the constructor, typed to its interface,
and bind the implementation in the composition root. Ask a factory for objects
that can only be created later or are needed once per use. Add a class to
valueObjects only if it represents a value rather than a collaborator.
Patterns: I need to create objects on demand, I need a default collaborator that can be replaced, I need WordPress state, such as the current post, I need to choose an implementation at runtime.
Principle: 7. Show the alternative to WordPress anti-patterns: constructors only store dependencies.
Checks: constructors of classes implementing Service contain only
assignments of a constructor parameter to a property of $this, poka-yoke
defaults and comments. Calls, computed assignments and control flow such as
if are reported at the statement that does the work.
Allows: $this->property = $parameter and
$this->property = $parameter ?? new Default(), where the parameter is nullable
and typed to an interface the default implements, as in
architecture.newOnlyWhereAllowed. Calls to parent::__construct() with
arguments are allowed so services can extend WordPress classes. Classes that
do not implement Service, including value objects, exceptions and
non-service infrastructure, are outside this rule's scope. Implementations of
Injector are also outside its scope: that interface extends Service so the
injector can be injected, but it bootstraps the object graph rather than acting
as a lifecycle service. Other factories that implement Service, including
TemplatedViewFactory, follow the same constructor rule as other services.
Configuration: constructorsOnlyAssign.allowed lists reviewed
Class::__construct exceptions. It is empty by default. The namespace of
Service and Injector comes from dependencyDirection.infrastructure.
Fix: keep the constructor to storing dependencies. Move the work into
register() or a callback, or into a factory if it is construction logic.
TemplatedViewFactory stores its optional locations in the constructor and
resolves default theme directories on the first create() call, keeping them
for later calls.
Pattern: I need to add hooks.
Principle: 7. Show the alternative to WordPress anti-patterns: creating an object never changes global state.
Checks: no constructor in the plugin's namespace calls add_action(),
add_filter(), remove_action(), remove_filter(), do_action(),
apply_filters(), register_activation_hook() or
register_deactivation_hook().
Allows: a closure the constructor creates, which runs later.
Configuration: none beyond the plugin's namespace.
Fix: keep the constructor to storing dependencies, and add the hooks in
register(), which the plugin calls at the right time.
Pattern: I need to add hooks.
Principle: 7. Show the alternative to WordPress anti-patterns, and the core idea of a service that decides once where it acts.
Checks: in a feature subsystem, add_action(), add_filter(),
remove_action() and remove_filter() are only called directly in
register(), activate() or deactivate() of a class implementing
Registerable, Activateable or Deactivateable, or in a method of one of
the scoped lifecycle interfaces, such as activate_site() of
SiteActivateable.
Allows: the infrastructure, which orchestrates the lifecycle, and the
composition root. A closure, even one created in register(), is a callback
and does not count as the lifecycle method. Calls made directly in a
constructor are reported by architecture.noHooksInConstructor instead.
Configuration: hooks.lifecycleMethods maps each lifecycle method to its
interface. The infrastructure's namespace and the composition root come from
dependencyDirection.
Fix: add the hook in register(). A hook that has to wait for a later
action belongs to a service that implements Delayed.
Patterns: I need to add hooks, I need to hook in later.
Principle: 7. Show the alternative to WordPress anti-patterns:
no is_admin() checks wrapped around hook calls, or hooking to an early
action just to wait for a later one.
Checks: register() does not call a request-context or hook-timing
function directly.
Allows: request-context and hook-timing functions everywhere else,
including in the closures and arrow functions register() adds as callbacks,
which run later. Infrastructure calls outside register() are unaffected;
principle 4 lets implementation details read WordPress state.
Configuration: hooks.contextFunctions lists the request-context
functions: is_admin, is_network_admin, is_user_admin, wp_doing_ajax,
wp_doing_cron, wp_is_json_request, is_customize_preview, is_singular,
is_front_page, is_home and is_archive. hooks.timingFunctions lists the
hook-timing functions: did_action, doing_action, did_filter,
doing_filter, current_action and current_filter.
Fix: for request conditions, implement Conditional and return the answer
from is_needed(). The plugin then never builds the service in a request
that does not need it. For hook timing, implement Delayed and return the
action from get_registration_action(), so the plugin defers the service
until that action. The two checks have separate messages under the same
identifier.
Patterns: I need a service only in some requests, I need to hook in later.
Principle: 7. Show the alternative to WordPress anti-patterns, and the capability interfaces of the core idea: the plugin waits until a service's condition can answer before building it.
Checks: when is_needed() of a class implementing Conditional calls a
configured query- or screen-dependent function directly, the class also
implements Delayed.
Allows: a Conditional that only calls request checks such as
is_admin(), classes that do not implement Conditional, and calls in other
methods, helpers, closures or arrow functions. Only direct calls in
is_needed() count. This rule checks for Delayed;
architecture.registrationActionKnown checks whether its action is known.
Neither proves that the action runs late enough for the condition.
Configuration: queryContextNeedsDelay.queryFunctions lists the
query-dependent functions: is_singular, is_single, is_page,
is_front_page, is_home, is_archive, is_search, is_404,
is_attachment, is_feed and is_main_query.
queryContextNeedsDelay.screenFunctions lists the screen-dependent functions:
get_current_screen. Set screenFunctions: [] to disable the screen check.
The capability interfaces' namespace comes from
dependencyDirection.infrastructure.
Fix: for query-dependent conditions, implement Delayed and return wp
or a later action from get_registration_action(). The plugin waits for that
action before asking is_needed(), so the query has run when the condition
reads it.
For screen-dependent conditions, return current_screen or a later admin action:
WordPress has not set the admin screen when services are normally checked at
plugins_loaded. The two checks have separate messages under the same
identifier. See I need to hook in later and
I need a service only in some requests.
Principle: 7. Show the alternative to WordPress anti-patterns, and the capability interfaces of the core idea: a delayed service must name an action it can wait for.
Checks: every declared Delayed service in the composition root returns
either a configured core action or an action starting with the plugin's hook
prefix. Failures name the service identifier, class and action, and state the
prefix to use. Callable declarations are resolved through the root's own
injector configuration.
Allows: core actions in either configured list and plugin-prefixed actions,
such as mwpd.basic_scaffold.ready. An empty hook prefix does not allow every
action. Empty or whitespace-only actions are reported only by
architecture.compositionRootContracts, which already requires an action.
Whether a core action fires in the service's request type, whether it runs
late enough for a condition, and dynamic actions WordPress builds from names
(such as load-{$page_hook} and admin_print_scripts-{$hook_suffix}) are
outside this check's scope.
Configuration: RepositoryLayout::COMPOSITION_ROOT selects the root.
RepositoryLayout::REGISTRATION_ACTIONS lists core actions with a fixed firing
order; RepositoryLayout::ADDITIONAL_CORE_ACTIONS adds admin_menu,
admin_init, current_screen, rest_api_init, wp_enqueue_scripts,
admin_enqueue_scripts, wp_head, wp_footer and admin_notices without
assigning them an order. Both lists form the known core set. A layout can
override them through its optional registration_actions and
additional_core_actions constructor arguments. The contract reads the
root's protected HOOK_PREFIX constant through reflection, so generated
plugins retain the check after renaming their namespace and prefix.
Fix: correct the action to a core name, or start the plugin's own action with its hook prefix. See I need to hook in later.
Principle: 13. One plugin, to arbitrary complexity: everything public carries the plugin's prefix, so several plugins built from this scaffold run side by side.
Checks: the names the plugin creates in WordPress's shared spaces start with the prefix for their kind:
| Kind | Functions | Name | Default prefix |
|---|---|---|---|
hooks |
do_action, do_action_ref_array, apply_filters, apply_filters_ref_array |
1st argument | mwpd.basic_scaffold. |
options |
add_option, update_option, delete_option, get_option and their _site_option variants |
1st argument | mwpd_basic_scaffold_ |
transients |
set_transient, get_transient, delete_transient and their _site_transient variants |
1st argument | mwpd_basic_scaffold_ |
meta |
register_meta, register_post_meta, register_term_meta |
meta key, the 2nd argument | mwpd_basic_scaffold_ |
assets |
wp_register_script, wp_register_style, wp_enqueue_script, wp_enqueue_style |
handle, the 1st argument | mwpd-basic-scaffold- |
postTypes |
register_post_type |
1st argument; full name at most 20 characters | mwpd_bs_ |
taxonomies |
register_taxonomy |
1st argument; full name at most 32 characters | mwpd_bs_ |
shortcodes |
add_shortcode |
1st argument | mwpd_basic_scaffold_ |
restRoutes |
register_rest_route |
namespace, the 1st argument | mwpd/basic-scaffold |
cron |
wp_schedule_event; wp_schedule_single_event, wp_unschedule_event; wp_next_scheduled, wp_clear_scheduled_hook |
hook: 3rd; 2nd; 1st argument, respectively | mwpd_basic_scaffold_ |
adminPages |
add_menu_page, add_options_page, add_management_page; add_submenu_page |
menu slug: 4th; 5th argument, respectively | mwpd-basic-scaffold- |
settings |
register_setting |
option group, the 1st argument, is a read and may name a core settings page; option name, the 2nd argument, always needs the prefix | mwpd_basic_scaffold_ |
ajax |
add_action with a known wp_ajax_ or wp_ajax_nopriv_ action |
the remainder after WordPress's action prefix | mwpd_basic_scaffold_ |
The same check applies where a name is created by a static method rather than
a WordPress function: the handle, the 1st argument, of the asset declarations
Style::file(), Style::inline() and Script::file(). A service declares its
asset there, and the infrastructure passes the handle on to WordPress later.
A name passes when PHPStan knows it starts with the prefix, or when it is built
from one of the kind's prefix constants of the class itself, as in
static::HOOK_PREFIX . static::SERVICES_FILTER. A name the rule cannot work
out fails, so build names from the prefix. Arguments unpacked from a constant
array are read from the array. The length limits come from the installed
WordPress stubs' register_post_type() and register_taxonomy() declarations.
They apply to the full constant string, including its prefix. A name built
from a configured prefix constant skips the length check because its final
length may be unknown.
Allows: for calls that only read a name, such as get_option(),
wp_enqueue_script() without a source, or firing a hook, the names WordPress
owns that the kind lists as allowed. wp_next_scheduled() is also a read;
scheduling and clearing cron events create or change the plugin's own names.
The option group in register_setting() is a read: it may use the prefix or
name a core settings page in settings.allowed (general, writing,
reading, discussion and media by default). A field on a core page must
join that page's option group. The option name is a write and always needs the
prefix; settings.allowed does not exempt it.
add_filter() and non-AJAX add_action() subscriptions are unchecked because
they subscribe to names other code owns. Only add_action() names known to
start with wp_ajax_ or wp_ajax_nopriv_ are checked, and their remainder
must carry the AJAX prefix. A known AJAX wrapper with an unresolved remainder
fails with the usual "cannot check" message. A name WordPress owns that the
plugin also has to write passes, reads and writes alike, when the kind lists it
as managed: a reviewed exception for state WordPress keeps on the plugin's
behalf, such as its entry in the uninstall_plugins option. A class listed as
a forwarder of a kind, WordPressAssets for asset handles, is not checked: it
only passes on handles that were checked where they were declared.
Configuration: prefixedNames.<kind> sets the kind's prefix, its
prefix constants, the allowed names it may read and the managed names it
may also write. Each kind lists all four, [] for none. A kind absent from
configuration is skipped. The defaults above follow WordPress conventions: underscores for
stored keys, shortcodes, cron hooks, settings and AJAX actions; hyphens for
asset handles and admin slugs; and the path-like mwpd/basic-scaffold for REST
namespaces (for example, mwpd/basic-scaffold/v1). Post types and taxonomies
use the shorter mwpd_bs_ so the prefix leaves room for a name within their
limits; the option prefix alone is already 20 characters. Hooks retain
mwpd.basic_scaffold. and the HOOK_PREFIX constant. A plugin generated from
the scaffold renames these settings together with HOOK_PREFIX and
SERVICE_PREFIX in its composition root. prefixedDeclarations.methods.<kind>
lists the static methods, as Class::method, whose 1st argument creates a name
of the kind, and prefixedDeclarations.forwarders.<kind> the classes that only
pass such names on; both are renamed with the plugin's namespace.
Fix: start the name with the prefix, or build it from the prefix
constant. Shorten overlong post type and taxonomy names, including the prefix,
to the WordPress limit. Writing a name WordPress owns needs a reviewed
managed entry; add one only for state WordPress keeps for the plugin itself,
and say why beside it.
Patterns: I need a name in a space WordPress shares, I need a public API for themes or other plugins, I need to load a script or style.
Principle: the hard rule not to weaken the gates.
Checks: suppressions in real PHP comments in the main plugin file,
src/, views/ and tests/php/ name the errors they silence. Reports are
per occurrence, at the offending comment line, including inside multiline
comments.
- PHPStan's line and next-line ignores are rejected because they cannot name
an identifier.
@phpstan-ignoremust name a dotted identifier such asargument.type; comma separated identifiers and a parenthesised reason are allowed. phpcs:ignoreandphpcs:disablemust name a dotted sniff, such asWordPress.Security.EscapeOutput, optionally with a code suffix. Comma separated lists are allowed; text after--is a reason, not a sniff name. A leading@is recognized too.phpcs:ignoreFileis always rejected, even with a name, because it silences the entire file.@psalm-suppressmust name an issue type such asUnresolvableInclude.
Allows: named suppressions, with or without a written reason; writing a
reason is recommended. Strings are not comments, and rule fixtures declared
in RepositoryLayout are excluded. PHPStan's file ignore, phpcs:enable,
phpcs:set, and configuration-level ignores in phpstan.neon.dist and
psalm.xml are outside this rule's scope. Named suppressions of architecture
rules are still rejected by
architecture.noSuppression.
Configuration: the shared suppression-check scope and rule fixture
exclusions in RepositoryLayout; no suppression allowances.
Fix: fix the code or use a suppression that names the error at its point
of use: // @phpstan-ignore argument.type (reason),
// phpcs:ignore Category.Sniff -- reason, or
@psalm-suppress IssueType reason. Explain why it is needed so the next
reader can assess whether it still applies.
Principle: the hard rule not to weaken the gates.
Checks: no inline @phpstan-ignore, @phpstan-ignore-line or
@phpstan-ignore-next-line in the main plugin file, src/, views/ or
tests/php/ names an architecture rule. phpstan.neon.dist, and any
baseline it includes, has no ignoreErrors entry for one, and keeps
reportUnmatchedIgnoredErrors on, so an ignore cannot outlive what it hid.
Allows: the fixtures of the architecture rules, which break them on
purpose. Ignores of other PHPStan, Psalm or PHPCS errors must name what they
silence, as checked by
architecture.suppressionsAreNamed.
Configuration: none.
Fix: fix the code. If the rule is wrong for a real case, open an issue
with needs: decision; an exception the maintainer accepts becomes an
allowance in the rule's configuration.
An ignore counts as aimed at a rule when it names its identifier, or when its
message pattern matches, or spells out, one of the phrases the rule's manifest
entry lists as signatures. An ignore limited to other identifiers does not
count. The check reads the configuration the way PHPStan does: replacing keys
such as ignoreErrors!, and includes given relative, absolute or with
%currentWorkingDirectory%.
RuleRegistrationTest also keeps the rules, RuleManifest and this page in
step:
- every identifier constant has a manifest entry;
- every entry names what checks it, and that is a PHPStan rule registered in
tests/php/PHPStan/rules.neonor a test method that exists; - every PHPStan rule is registered, and named by an entry;
- every signature still appears in a rule's messages;
- no rule spells an identifier out instead of using its constant;
- every section on this page belongs to a rule in the manifest;
- every rule a pattern lists under Rules is in the manifest, and leads
back to the pattern, as its
patternor through a link in its section on this page; and every rule'spatternlists the rule.RuleManifestTestchecks that thepatternanchor exists.
Principle: 5. One composition root builds the object graph, 11. Lifecycle steps are idempotent, and the capability interfaces of the core idea.
Checks: the real composition root, and every service it declares, built through the plugin's own injector configuration:
- every declaration, a class name or a callable that returns one, is a class
implementing
Service; - a
Delayedservice names an action to wait for, and aHasDependenciesservice only depends on services the root declares; - dependencies contain no cycles, including self-dependencies; each cycle is reported once with the service identifiers along its path;
- a service registers at the same action as its dependencies or later, using
its
Delayedaction orplugins_loadedfor an undelayed service; - the plugin accepts its own injector configuration, which it validates as it applies it, for example that each binding points to a subtype;
- the plugin can build every service from its own bindings, arguments and
delegations, and what it builds is a
Service; - building a service adds, removes or fires no hook, and registers no activation or deactivation hook, not even through a collaborator its constructor creates;
- every declared service implementing
Registerable,ActivateableorDeactivateablecan runregister(),activate()ordeactivate()twice without changing the recorded state on the second call, and so can every method of the scoped lifecycle interfaces it implements, such asactivate_site()oruninstall_network(), called with the context of site 1 on network 1. The check records hook additions and removals, cron events, option and transient writes, and post, user, term and comment meta writes. Failures name the service, method and effect; exceptions in either call are reported as problems.
Allows: the tests stub the WordPress functions the wiring calls, such as
get_stylesheet_directory(), and use stand-ins for WordPress classes such as
WP_Post. They never add a binding the composition root does not have. WordPress writes are
modelled in memory: adding an existing option or unique meta row is a no-op,
setting a value replaces it, and non-unique meta additions append. Hooks are
keyed by hook name, priority and callback identity, as in WordPress. Re-adding
the same callback at the same priority replaces the entry; a fresh closure,
a different object or method, or a different priority adds an entry. Removing
an existing entry changes state; removing a missing entry leaves it unchanged.
Actions and filters share hook entries, and fired hooks retain their call
history. Cron events are keyed by hook, timestamp and md5( serialize( $args ) ),
with recurrence stored per event. Scheduling the same event replaces it;
a different timestamp or argument array adds one. wp_next_scheduled() returns the
earliest timestamp matching the hook and arguments, or false.
wp_clear_scheduled_hook() removes events matching the hook and arguments
and returns the number removed; wp_unschedule_event() also matches the
timestamp and returns true even when nothing matched. Single events use the
same model without the ten-minute duplicate window. This does not check the
plugin's own register_services() orchestration (#26), which services activation,
deactivation and uninstall reach and in which sites
(tests/php/Unit/ServiceBasedPluginTest.php, tests/php/Unit/ScopedLifecycleTest.php
and tests/php/Unit/UninstallLifecycleTest.php cover that),
or database and filesystem effects Brain Monkey cannot see. Dependency graph
checks skip missing or invalid declarations already reported by the contract.
Ordering checks silently skip an edge if either action is outside the known
order; architecture.registrationActionKnown validates action names separately.
They do not evaluate whether a Conditional dependency is needed in a
particular request.
Configuration: RepositoryLayout::COMPOSITION_ROOT names the composition
root. A service added to it is checked without changing the test.
RepositoryLayout::REGISTRATION_ACTIONS lists core actions in firing order,
from plugins_loaded through bootstrap and front-end routing to shutdown,
following the WordPress action reference.
Hooks inside other callbacks, repeatable query hooks and theme-controlled
hooks are omitted because their relative order is not fixed. A layout can
override the list through its optional registration_actions constructor
argument; the contract accepts an optional layout and otherwise uses
RepositoryLayout::of_plugin().
Fix: bind what a service needs in the composition root, declare the services it depends on, remove dependency cycles, and delay a service until its dependencies' actions or later (or register the dependencies earlier). Keep constructors to storing dependencies. Guard each lifecycle step so a second run does nothing, or make it set rather than add.
Patterns: I need to add a feature, I need to set something up when the plugin is activated, I need to clean up when the plugin is uninstalled.
Principle: 5. One composition root builds the object graph, and the capability interfaces of the core idea.
Checks: a class implementing Registerable, Conditional, Delayed,
HasDependencies, Activateable, Deactivateable, ObservesRegistration or
one of the eight scoped lifecycle interfaces (SiteActivateable,
NetworkActivateable, SiteDeactivateable, NetworkDeactivateable,
SiteInitializable, SiteUninitializable, SiteUninstallable,
NetworkUninstallable) also implements Service.
A Delayed class also implements Registerable or HasAssets: waiting for an
action only makes sense when the service has hooks to register or assets to
load. Inherited interfaces count,
including on abstract classes.
Allows: interfaces and traits, ordinary classes with no lifecycle capabilities, and services implementing the capabilities they need. The infrastructure and the configured composition-root classes orchestrate services and are outside this check.
Configuration: capabilitiesOnServices.service names the service marker,
capabilities lists the lifecycle interfaces, and delayed, registerable
and hasAssets name the interfaces whose combination is checked. All are fully qualified
names, renamed together with the plugin's namespace. The orchestration
exclusions come from dependencyDirection.infrastructure and
dependencyDirection.compositionRoot.
Fix: implement Service so the plugin can orchestrate the class; for a
Delayed class, implement Registerable and add its hooks in register(), or
HasAssets if all it does is load scripts or styles.
Declare the service in the composition root as shown in
I need to add a feature.
Patterns: I need to add a feature, I need to see why a service did not run, I need to load a script or style.
Principle: 5. One composition root builds the object graph.
Checks: every concrete class in a feature subsystem that implements
Service, directly or through inheritance, is declared in the composition
root's get_service_classes(). Callable declarations are resolved through the
root's configured injector, just as in compositionRootContracts.
Allows: abstract classes, interfaces, traits, non-service classes, classes
directly in the plugin's root namespace, the infrastructure, exceptions and
excluded namespaces. Services built by a factory or another route are allowed
when explicitly listed in RepositoryLayout::SERVICES_BUILT_ELSEWHERE, with a
description of that route containing more than whitespace. Services supplied
by other plugins through the services filter are outside this check.
Configuration: production paths and SERVICES_BUILT_ELSEWHERE come from
RepositoryLayout; COMPOSITION_ROOT selects the root. The plugin namespace,
excludedNamespaces, dependencyDirection.infrastructure and
exceptions.namespace come from parameters.architecture in
phpstan.neon.dist, so generated plugins keep the check after renaming.
Fix: declare the named class in get_service_classes(), or list it in
RepositoryLayout::SERVICES_BUILT_ELSEWHERE with the factory or other route
that builds it. See I need to add a feature.