A Rule in Detail
What every custom rule must strictly follow: declare its decisions, modify code only after an accepted report,
remain completely stateless and idempotent, and configure the RuleInfo attribute accurately. The engine and
RuleTester automatically enforce most of these contracts, and this rigorous foundation is precisely what allows all
rules to run side by side without artificial priority numbers. The page also describes what a rule gets from the engine: the
values of its decisions, the context of the file, analyses and the types of the code.
Two Forms of a Rule
Every rule in DressCode extends the base class DressCode\Rule. Rules come in two distinct forms depending on the
nature of the task:
NodeRuletraverses specific nodes and tokens in the concrete syntax tree, inspecting and mutating them inenter()andleave()methods. Most rules are implemented this way, and this whole page is about them.GapRulenever visits nodes directly. Instead, it submits declarative claims about the whitespace that should exist between tokens, leaving their evaluation to the engine. It is written completely differently and has its own dedicated page.
A rule class is always strictly one or the other. If an inspection appears to need both, it is in fact a pair of rules, each governing its own distinct decisions.
The Shape of a Rule
A rule extends DressCode\NodeRule and carries the mandatory #[RuleInfo] attribute:
#[RuleInfo(
Stage::Structure,
modifiesComments: false,
requires: [],
typesRequired: false,
analyses: [],
decisions: [],
reads: [],
)]
final class NoDebugCallsRule extends NodeRule
{
// ...
}
Notice that the attribute defines neither a name nor a description for the rule. A rule is identified directly by its class, and users in their configuration never interact with rules, but with their decisions, each of which defines its own description.
- The stage (
Stage) determines which of the three execution stages the rule runs in.Structureis reserved for structural code modifications (rewriting expressions, removing imports),Formattinghandles whitespace and line breaks, andFinishingperforms final cleanup (indentation, line endings, trailing whitespace, line length, comments, and phpDoc). Stages execute strictly in this order, ensuring formatting rules operate on code after structural refactorings are complete. - Set
modifiesCommentstotruestrictly when the rule intentionally modifies comment text. Otherwise,RuleTesterrigorously verifies that no comments are lost or altered, the most common pitfall of careless automated fixes. requiresdefines the rule's environment constraints using the syntax of therequiresection ofcomposer.json, for instance['php' => '>=8.1']for a rule emitting newer syntax (like the0o755octal literal) or['acme/mailer' => '>=3.3 <5.0']for a construct that a later release of the library removed again;'*'in place of a version is enough when only the presence of a package matters. The entire version range the project supports in itscomposer.jsonmust satisfy the constraint; otherwise the rule skips itself automatically, so no preset or set has to watch for this. A bare version without an operator is rejected, because it would disable the rule for all other releases, and features of PHP 8.0, the baseline supported release, need no constraint.- Set
typesRequiredtotruefor rules that make no sense without static type analysis, specifically, without theAnalyses\Typesanalysis, which is available only whentypeAnalysis: phpstanis configured. If types are unavailable, decisions enabled by presets quietly step aside; if explicitly declared in project configuration, DressCode halts with a configuration error. Rules for which types are merely an optional enhancement should leave this parameter unset and check for analysis availability viafindAnalysis()(see Types of the Code below). analysesnames every analysis the rule queries (including those called by its helper classes), e.g.[Types::class, NameResolver::class]; rules withtypesRequired: truemust listAnalyses\Typeshere.RuleTestervalidates fixtures under strict mode and rejects unlisted analyses, making all dependencies explicit directly in the attribute.decisionslists paths of external decisions that the rule does not declare itself but follows: they activate the rule just like its own decisions, and the rule reports violations under them. These typically include engine decisions (such asfile.lineLength, allowing a rule to wrap its constructs at the same boundary as all other rules) or decisions shared across multiple rules in a plugin (see A Shared Decision).readslists decision paths that the rule merely inspects passively without enforcing: they do not activate the rule and the rule does not report under them, but their values are accessible inconfigure(). This allows a rule to defer to another rule's map, for example,NoDeprecatedMembersRulestays silent on members already governed byupgrading.api.replacedMembers, whether the rule of that map runs or not.
Risk information does not belong in RuleInfo. Risk is always a property of a specific occurrence in code, and
rules specify it dynamically when invoking report(), even if every fix the rule makes happens to be risky (see Risky Fixes below).
Which Nodes and When
public function getVisitedNodes(): array
{
return [FunctionCallNode::class];
}
This method returns an array of node classes (or Token::class) for which the engine will invoke
enter() and leave(). Matching is evaluated via instanceof, meaning
StatementNode::class matches any statement and Node::class matches absolutely everything. The narrower
your array, the faster the file traversal. Returning an empty array indicates that the rule operates exclusively in
beforePass() and afterPass(), which the engine calls at the start and conclusion of every pass over a
file (how whole-file rules are implemented).
enter() is called when stepping into a node (before its children are visited); leave() is called upon
exit after all children have been traversed. If a rule replaces or deletes a node in enter(), the engine skips
descending into its children and does not call leave() for it.
The Decisions a Rule Enforces
What a rule enforces is declared in its static getDecisions() method as an array of
DressCode\Decision objects. A rule must declare at least one decision (either its own, or one referenced in the
attribute's decisions parameter): every violation is reported under a specific decision, and DressCode immediately
rejects a rule that has none with the error Rule `Acme\CodeStyle\NoDebugCallsRule` declares no decision. The
decisions of all rules (from the engine, plugins, and the project) collectively form the catalogue: used to validate
configurations, populate dresscode explain and dresscode catalogue, and offer suggestions when a key is
mistyped.
public static function getDecisions(): array
{
return [
new Decision('acme.debugCalls', Domain::state('forbidden'), 'A statement calling a debugging function is removed'),
];
}
The path is the identifier by which users interact with the decision: it is the configuration key, the label of a
finding in the terminal, the identifier in dresscode:ignore comments, in fixRisky, in
severity, and in the baseline. The first segment represents the section. Project rules operate in
project, plugin rules in a section that its manifest names after the plugin (PluginManifest::$section),
and the engine in its own dedicated sections. Paths outside their designated section are rejected, as are duplicate paths declared
by two different rules.
Because users write and read the path, its name matters most. The path names a thing in the code, not the step the fix takes,
and the value says how the thing is written: acme.debugCalls: forbidden, not
acme.removeDebugCalls: true. The built-in catalogue uses established words for values: forbidden and
required for what must not, or must, appear in the code (in the upgrading section also for a construct
of newer PHP and for replacing something deprecated); sameLine and nextLine for the position of a token;
a code sample in quotes for a shape; and a number for blank lines. Where a thing appears in several places, each one gets its own
key (braces.position.class, braces.position.function), and a parameter that only refines something
carries the name of what it refines (mistakes.debugOutputFunctions). Paths are written in camelCase.
By convention, a rule class is named after the state it enforces, with the suffix Rule, so
ExceptionMessagePeriodRule enforces acme.exceptionMessagePeriod; ruleUrl builds the
address of the rule's page from this name, without the suffix and with a lowercase first letter. A plugin that follows these
conventions fits in beside the built-in catalogue.
The description is an English sentence without a trailing period explaining what the rule does when not set to
keep, with code constructs enclosed in backticks. The notes parameter adds sentences about what the
decision does not cover; dresscode explain renders them below the main description.
Decisions exist in three distinct forms:
- A requirement activates a rule: the rule runs wherever any configuration layer sets the requirement to a value other
than
keep. Every requirement acceptskeepautomatically, and if omitted from configurations and presets, it requires nothing. It has no default value, andDecisionwill reject one. - A parameter (
parameter: true) refines a requirement's behavior without activating any rules on its own, and does not acceptkeep. Instead, it defines a mandatory default value (default:). Lists of exceptions or numerical thresholds are parameters: their presence in a configuration file must never activate a rule on its own. - A fact (
fact: true) describes the project environment and is merely monitored by rules (for instance, the list of declarations in project namespaces). It is never narrowed by--only. Facts are declared by the engine, and a custom rule rarely needs one.
new Decision('acme.debugMethods', new Names, 'The methods whose calls count as debugging calls, as `Class::method`', parameter: true, default: []);
The domain (Domain) defines what values a key accepts, how values are normalized, and how values from
different configuration layers merge:
| domain | what it takes | example in the configuration |
|---|---|---|
Domain::state('forbidden'), state('required'), state('required', 'forbidden') |
Presence: the construct must or must not exist; in the upgrading section, required writes a
construct of a newer PHP or library |
acme.debugCalls: forbidden |
Domain::placement() |
Token placement: sameLine or nextLine |
braces.position.class: nextLine |
new Words([...]) |
Words from the domain's own list, each with a description; with tolerance: true, accepts a list of words where
each is valid and the first is used for writing |
literals.quotes: single |
new Shapes([...]) |
Construct shape written as single-quoted code examples; only the rule reads the word that names the shape | spacing.call: 'foo($a, $b)' |
new Count, Domain::blankLines() |
Integers, closed ranges 1-2, open ranges 1+, or words like none |
blankLines.aroundMethods: 2 |
new Names |
Arrays of identifiers, patterns, or sort orders; ... inherits items from lower layers |
mistakes.debugOutputFunctions: [..., dump, bdump] |
new Map($domain) |
A map of names or wildcard * patterns to values of another domain |
blankLines.beforeStatement: {return: 1} |
new Flag, new Text |
Booleans yes/no (parameters only) and free text strings |
The value keep is never explicitly listed in a domain's allowed values: every requirement accepts it
automatically, maps accept it per item, and applied to an entire section or group, it applies to everything below it. A domain
never dictates report severity. That is handled exclusively by the severity configuration key. Never invent custom
terms for “leave this alone”; universal keep is the only supported value.
A Shared Decision
A decision usually belongs to one rule, which returns it from getDecisions(). When two rules of a plugin with
independent logic enforce one thing, for example debugging output in a call and in a comment, the plugin's manifest declares the
decision in decisions, and both rules name it in #[RuleInfo(decisions: [...])]. The user writes one key
that turns on both rules, and the findings of both are reported under it:
return new PluginManifest(
rules: [DebugCallsRule::class, DebugCommentsRule::class],
section: 'acme',
decisions: [new Decision('acme.debugOutput', Domain::state('forbidden'), 'Debugging output left in the code')],
);
#[RuleInfo(Stage::Structure, decisions: ['acme.debugOutput'])]
final class DebugCommentsRule extends NodeRule
{
// ...
}
A rule may also name a decision of the engine, such as file.lineLength, and follow it just like the rules of the
engine do. A rule that only reads a decision without enforcing it names it in reads instead of
decisions and finds the value in its Values, even when the run leaves out the rules that enforce it.
Tests find shared decisions automatically: RuleTester reads the plugin from the key
extra.dresscode.plugin in the composer.json of the package where the rule lives.
Values in the Rule
Final configuration values for a file are delivered to the rule's configure() method as a Values
object. The engine invokes this method once for each unique combination of configuration layers across your files. The rule
precalculates whatever data structures it will need and stores them in instance properties:
public function configure(Values $values): void
{
$names = $values->get('mistakes.debugOutputFunctions')->getNames();
$this->functions = array_fill_keys(array_map(strtolower(...), $names), true);
}
Calling $values->get($path) returns a Value object with the resolved value of the decision (or a
parameter's default if nobody changed it), and a getter matching the domain reads the value from it: getWord(),
getShape(), getCountRange(), getNames(), getEntries(), getFlag(),
getText(). Read a decision that can be keep using $values->find($path): it returns
null for an inactive decision, so you write $values->find($path)?->getWord(), and
$values->isKept($path) returns the same as a boolean. Querying a path the catalogue does not know via
get() or find() throws an exception, never returning null;
$values->has($path) checks whether the catalogue knows it (a run of only a few rules knows only their
decisions).
Rules may also read decisions owned by other rules. The example above reads the list of debugging functions from the engine
parameter mistakes.debugOutputFunctions, which the project may have already configured, rather than introducing a
redundant key; this way the project tells all rules at once, with one list, what a debugging function is. In the same way, rules
generating code can query conventions like quote preferences.
A rule with a single requirement reports under it automatically and omits the path from report(). A rule that
governs multiple requirements must specify the path with every call:
$context->report($node, 'The `dd()` call must not stay in the code.', decision: 'acme.debugCalls');
Reporting under a requirement set to keep or excluded by --only records nothing and returns
false. Rules therefore don't need to check values before every report() invocation. Reporting under an
undeclared path or under a parameter violates the contract.
The $values->isSelected($path) method answers a different question: whether the requirement is
actively being reported and fixed in the current run. This distinction arises when using --only, which narrows the
scope of a run without changing configured values. Generated code must always follow get() (representing the full
configuration); isSelected() is merely an optimization allowing rules to skip work for requirements that are not
being reported.
Report First, Fix Second
This is the most critical rule of the entire development contract: the syntax tree may only be modified after
report() has returned true.
$statement = $node->parent;
if (
$statement instanceof ExpressionStatementNode
&& $statement->parent instanceof NodeList
&& $context->report($node, 'The `var_dump()` call must not stay in the code.')
) {
$statement->remove();
}
The example above safely removes the entire statement wrapping the call, because remove() can delete items only
from a list. The rule verifies that this is possible before calling report(): calls inside another expression or
statements in slots without braces (like an if body without braces) are left alone.
report() returns false if the finding is suppressed by a comment on that line, or if the fix is
classified as risky and the run did not permit it. In either case, the code must not change. Findings recorded in a baseline file
do not cause report() to return false: the violation is hidden from reports, but the rule is fully
permitted to fix it. The engine does not rely on developer discipline: the syntax tree internally tracks every mutation, and the
engine strictly pairs every change with a successful report from the exact same invocation. Modifying the tree without reporting,
or after a report that returned false, violates the contract. During standard execution it raises a warning; under
--strict-rules and inside RuleTester, it throws an exception.
Risky Fixes
Fixes that can alter runtime behavior are reported with the risk parameter directly at that specific occurrence.
The parameter value identifies what would resolve the risk: Risk::TypeUnknown indicates an unverified type (which
neither declarations nor PHPStan types can confirm),
Risk::NameUncertain flags function ambiguity in namespaces (which nameResolution: certain
resolves), and Risk::BehaviorChanges denotes human judgment where an edit alters semantics by its nature or depends
on code the run does not see. The because parameter provides a sentence explaining what could go wrong, when the
cause alone does not make it clear; in a strict run, passing because without risk is rejected. This
sentence is rendered alongside the message, never inside it: the message describes the violation and must remain stable regardless
of whether type analysis is active.
if ($context->report($foreach, 'The loop must be written with `array_any()`.', risk: Risk::TypeUnknown,
because: 'the loop may go through an object, which `array_any()` does not take')) {
// ...
}
Such a report returns false until the project approves the decision in fixRisky or the run receives
--fix-risky. Until then, the rule leaves the code untouched, and the finding remains in the summary of unperformed
fixes (as a warning for TypeUnknown and NameUncertain, and as an error for
BehaviorChanges). A rule can fix safe occurrences while reporting risky ones within the same pass; even a rule whose
fixes are always risky passes risk with every call. A fixture with // risky in its header tests how the
rule behaves when risky fixes are permitted.
A risky fix may alter program behavior, but it must never emit code that PHP cannot compile. Where that would depend on a file outside the reach of the run (such as a subclass in another library that overrides the method with the old signature), the rule stays silent: permission to make a fix that may produce code PHP cannot compile makes no sense.
Where safety depends on types, rules return one of three states from the Tristate enum: a definitive yes (the fix
is safe), a definitive no (the rule stays silent, because a risky fix must never offer advice known to be incorrect), or unknown
(the fix is risky with Risk::TypeUnknown). Visible declarations (parameter, property, or return types) provide the
initial answer, and PHPStan types resolve what remains open.
Fixes protect the behavior of functioning code. An edit is not considered risky if all it eliminates is an error
or warning that the original code would raise only past the point where the answer is already determined: for instance,
array_any() instead of count(array_filter()) halts on the first matching element and skips evaluating
the rest of the array. Nor is a fix risky if it updates code relying on behaviors that PHP marks as deprecated across all target
versions.
A Finding Without a Fix
For findings that a rule cannot fix automatically and only reports, pass fixable: false. report()
will always return false, and the report is never marked risky. Otherwise, an unfixable report with a risk flag would
look like an edit waiting for approval, leading summaries to suggest --fix-risky. For example,
mistakes.strictArgument merely reports explicit false arguments in in_array() calls because
the author wrote them deliberately:
$context->report($strict, 'The `in_array()` call must pass `$strict = true`.', fixable: false);
RuleTester catches a forgotten declaration: a report without fixable: false that remains in code
after the final steady-state pass violates the contract and fails the test. Similarly, a fixture with // risky fails
if an unperformed risky fix remains after its run, because permission was granted yet the fix did not occur.
Where a Finding Belongs
Reports are bound to a specific node or token. If a problem resides in whitespace or a comment, report it with the
corresponding trivia item (the whitespace or comment attached to the token) via
report($token, $message, trivia: $trivia): the violation receives the exact line number of that trivia, allowing
inline dresscode:ignore comments on that line to find it; otherwise it is reported on the line of the token. To check
whether a finding would be silenced by a comment without recording a violation, call
$context->isSilenced($at, $decision, trivia: $trivia).
Rules do not set report severity: every violation is an error by default until softened to a warning via the severity key.
Two additional parameters handle situations where a violation was caused by another fix in the same run. A rule
aligning a line against another line (such as indentation) passes follows: with the token opening that reference
line; a rule validating an entire line's layout passes byLine: true. If a fix in the same run opened or closed that
line (for follows:, also shifted it), the report follows from it and the terminal prints it indented directly under
the fix as a Then also line (see Output Formats).
The Text of the Message
Report messages describe code, not developers, and never issue commands. A message is a complete English sentence ending with
a period. It follows one of three standard formats: expected state (Expected a single space after the comma.), a
convention (The opening brace must be on its own line.), or an observation
(Function `foo()` is deprecated.). Specific identifiers and values belong in the message; the decision path does not,
as the output formatter appends it automatically. Code constructs (class names, function names, variable names, operators, or
values) must be enclosed in backticks as in Markdown; the console colors them and the other outputs print them as they are. An
expression, a string or a comment from the code can contain a backtick, so insert those using
Violation::formatCode($code), which safely wraps them in multiple backticks.
Stateless and Idempotent
A single instance of a rule serves the entire run across all files. State specific to a single file pass belongs exclusively
in the $context->passStorage array, which the engine initializes empty before every pass; class properties are
reserved strictly for data precomputed in configure().
Rules run repeatedly until the syntax tree stops mutating. A rule must therefore be strictly idempotent: running it
over its own output must produce zero changes. Furthermore, it must not depend on pass ordering or pass count (which the context
intentionally conceals). If two rules enter an infinite loop undoing each other's changes, the engine detects that the tree has
returned to a previous state and reports the file as a failure, naming both rules. RuleTester automatically verifies
idempotence: running the rule a second time over its own output fails if any further mutations occur.
What the Rule Knows About the File
Everything a rule needs to know about the current file is exposed on the context: $context->file is the root
syntax tree (FileNode), $context->path the relative path, $context->style the
configured style (indentation, line endings, tab width, maxLineLength, the kinds of constructs split to fit the line
width lineSplits, and import formatting imports), and $context->phpVersion the target
PHP version.
Rules whose code generation depends on the target PHP version (as opposed to whether the rule runs at all, which is what
requires is for) inspect $context->phpVersion. It is a major.minor string that must be
compared using version_compare(), not standard comparison operators (the string '8.10' is not greater
than '8.9'):
if (version_compare($context->phpVersion, '8.4', '>=')) {
// ...
}
What the Tree Allows
Node slots are updated via assignment ($if->condition = $expression), nodes are replaced using
replaceWith(), and removed using remove(). Token text and trivia are modified via their own dedicated
methods. Parent references and the token index are maintained automatically by the syntax tree (see Modifying the Tree). Rules must additionally observe the following
guidelines:
- Mutate sibling nodes in a list from the callback of their parent (
FileNode,BlockNode,ClassNode) or fromafterPass(), never directly fromenter()of the item currently being visited. The engine does not recompute the active traversal list on the fly. - A rule may replace only the node it was passed or one of its descendants, never an ancestor.
- Do not build new constructs by manually concatenating tokens. Use the parser (
Parser::parseExpression(),parseStatement(),parseType(),parseName()), or assemble nodes from existing parts using the staticof()factory of their class (FunctionCallNode::of(),NewNode::of(), etc.). When substituting an expression into the position of another, useExpressionNode::replaceWithExpression(), which handles required parentheses automatically. - Comments must never be discarded unless the rule explicitly declares
modifiesComments: true. Before modifying nodes, verify comment presence usingToken::hasComment(),Token::hasCommentUpTo(), orNode::hasInnerComment(); remove comments exclusively viaremoveTrivia(). - The newline closing a token's line belongs in its trailing trivia (
trailingTrivia), not in the leading trivia of the subsequent token. Helper methodsensureStartsLine()andsetBlankLinesBefore()handle this correctly, so build upon them. - To check whether expressions are the same or safe to evaluate twice, use
Node::matches()andExpressionNode::isRepeatableRead(). Do not re-implement these checks.
Analyses
Complex calculations about a file that are needed by multiple rules belong in an analysis. An analysis is a plain class whose
constructor accepts a FileNode (or no parameters). A rule requests it directly from the context:
$resolver = $context->getAnalysis(NameResolver::class);
if ($resolver->isGlobalFunctionCall($node, 'var_dump')) {
// ...
}
The engine instantiates an analysis on first request and caches it until the syntax tree mutates. After any mutation, the cache
is cleared and subsequent calls instantiate a fresh analysis. An instance held in a local variable reflects the tree prior to
mutation; a rule must therefore call getAnalysis() again after making changes, or extract required data before
mutating.
The exception is an analysis implementing Analyses\PassAnalysis: the engine computes it once on first request in a
pass and preserves it until the pass concludes, even across tree mutations (recalculating it after every minor edit would be
prohibitively expensive). A node inserted during the pass will have no entry in it, so rules query it safely using
?->.
Built-in analyses include PhpSyntax\Analyses\NameResolver (namespaces, imports, name resolution),
PhpSyntax\Analyses\Scope (function/class boundaries, $this availability),
DressCode\Analyses\PhpDoc (docblock ASTs), PhpSymbols (built-in PHP functions, classes, and constants),
PhpSignatures (built-in parameter signatures), and Types (static type analysis from the
project's PHPStan, the only built-in PassAnalysis).
Custom analyses taking a FileNode require no registration. Only analyses requiring custom construction need a
factory taking the tree and file path; plugins declare them in analyses in their manifest, and projects register them
under analyses in their configuration.
Calling getAnalysis() for an analysis unavailable in the current run throws an exception. Static types are
available only when typeAnalysis: phpstan is configured; rules for which types are optional should call
$context->findAnalysis(Types::class), which returns null when the run has no types.
Rules never query each other directly. What two rules in the same plugin share is a shared
decision from the manifest: the rule enforcing it names it in decisions, and the rule reading it names it in
reads. Methods on built-in rules are not public API; what rules need from them is exposed via CodeWriter
(see Names of Functions and Classes below).
Types of the Code
The Types analysis answers semantic questions that the syntax tree cannot answer on its own. PHPStan's internal
data structures remain encapsulated; rules query high-level methods:
findMember($node)returns anAnalyses\Member(the constant, method, property, or constructor the expression refers to) along with the class declaring it. Resolution tracks the true declaration rather than syntax:$order::STATUS_PAID,Order::STATUS_PAID, andself::STATUS_PAIDall yield the exact sameMember.findMemberAccess($node)returns anAnalyses\MemberAccess: access resolved by the receiver object's type, even for members that no class declares in newer releases. Rules that fix an API a library has removed query this method. Callables written as arrays ([$order, 'paid']) are resolved viafindCallableMethodAccess().findDeprecation($member)returns anAnalyses\Deprecationdescribing the member's@deprecatedannotation, ornull.isOfType($expression, 'array')returns aTristateindicating whether an expression matches a given type; types use phpDoc syntax (int|string,list<int>) with fully qualified class names. Call this method only when no specialized query covers your use case.
$types = $context->getAnalysis(Types::class);
$member = $types->findMember($node);
$deprecation = $member === null ? null : $types->findDeprecation($member);
if ($deprecation !== null) {
$context->report($node, $member->describe() . ' is deprecated' . $deprecation->formatDescription() . '.', fixable: false);
}
For the class Acme\Shop\Order, whose constant carries @deprecated use Order::StatusPaid, this example
reports Constant `Acme\Shop\Order::STATUS_PAID` is deprecated: use Order::StatusPaid. at
$order::STATUS_PAID. Rules where types merely enhance precision call findAnalysis() instead of
getAnalysis() and handle absence gracefully:
$context->findAnalysis(Types::class)?->isOfType($expression, 'array') ?? Tristate::Maybe. Without types, the
rule breaks nothing: it simply reports more edge cases as risky or leaves them untouched.
Names of Functions and Classes
NameResolver understands what cannot be deduced from an isolated file: which functions and constants the project
declares in namespaces (as configured via namespaces and nameResolution). An unqualified call inside a
namespace can target a function of that namespace, and unless the project ruled this out using
nameResolution: certain, every automated fix of such a call rests on an assumption. The GlobalCalls
helper resolves both: which global function a call targets, and what specific risk of collision exists:
if (!$node instanceof FunctionCallNode || GlobalCalls::findFunction($node, ['sizeof' => true], $context) === null) {
return;
}
$because = GlobalCalls::findUncertainty($node, $context);
if ($context->report($node, 'The `sizeof()` call must be written `count()`.', risk: $because === null ? null : Risk::NameUncertain, because: $because)) {
$node->name->text = CodeWriter::spellFunction('count', $node->name, $context);
}
findFunction() accepts target function names as array keys (values are ignored, allowing rules to pass their data
maps directly) and returns the called function name in lowercase, or null. findUncertainty() returns the
textual explanation of the risk (e.g. the namespace may declare `sizeof()`), or null if the call is
provably global. Never build replacement names by concatenating strings: CodeWriter::spellFunction() emits an
unqualified name if the original was bare and the new name introduces no ambiguity; otherwise, it prepends a backslash (see Functions and Constants in Namespaces for details).
NameResolver itself answers the same at a lower level. Calling isGlobalFunctionCall($node, 'is_null')
returns true for the global function, while recognizing that App\is_null() from your list is not global;
under certain, this answer is definitive, otherwise it is an assumption. Calling
getUnqualifiedResolution('is_null', SymbolKind::Function, $node) specifies where the name points: definitively to the
global namespace (Global), definitively to the namespace (Namespaced), or to the global namespace only
assuming the namespace doesn't declare it elsewhere (Uncertain). Flag a fix as risky exclusively for
Uncertain, and therefore never in a project configured with certain.
Class names should be written using CodeWriter::writeClass($class, $node, $context): it inserts the name in the
shortest valid form allowed by the file context, adding an import where needed, formatted according to imports.*
decisions ($context->style->imports), even in runs where import rules are not active. Because it can mutate the
syntax tree, invoke it strictly after report() has returned true, never while building report messages.
To shorten an existing identifier without inserting a new one, use NameResolver::shortenName().
A Map with Data
A rule that rewrites code based on lists from projects or libraries uses a map: the domain Map with
Data values and a validation schema that parses items once configuration layers merge. This is how
nette.flagsAsNamedArguments from the dresscode/upgrade-nette package operates: its key is an invocation
signature and its value maps bitwise flags to named arguments:
public static function getDecisions(): array
{
return [new Decision('nette.flagsAsNamedArguments', new Map(new Data, grammar: self::createGrammar()), 'A call passing the named arguments its method takes for the flags of an integer')];
}
public function configure(Values $values): void
{
$this->map = MemberMap::fromValues($values, 'nette.flagsAsNamedArguments', self::readFlags(...));
}
The grammar is a schema from the nette/schema library; for keys matching members
and argument signatures, Upgrading\MemberMapGrammar::createMapSchema() constructs it, ensuring plugin maps parse keys
identically to engine maps. $values->readMap() returns schema-validated items, and
Upgrading\MemberMap::fromValues() compiles them into an efficient lookup map by member name:
getEntries() returns items for a name, has() checks existence, and findCall() matches an
invocation item by its argument shape. This map can be populated both by project configurations and by package data files, which name it by its full path.
Testing
Every rule must be backed by fixtures and verified using RuleTester, which automatically validates output
correctness, report precision, and full contract adherence: Testing
Rules.