How to Write Your Own Rule
From writing your first test to running a custom rule across your codebase in a single afternoon: define the
decision your rule enforces, specify the syntax tree nodes you want to inspect, write your conditions alongside the automated fix,
and let RuleTester handle everything else.
What We Are Going to Write
Every team has a few bespoke coding conventions that no standard covers because they belong to that team alone. Take this
common example: an exception message is a complete sentence and must end with a period. A statement like
throw new InvalidArgumentException('The name must not be empty') should therefore automatically become
'The name must not be empty.'. For years, I watched for this manually in code reviews because writing a custom sniff
for PHP_CodeSniffer was more trouble than it was worth. In DressCode, we can implement this cleanly in about fifty lines, and
we'll write them together.
The rule extends classes of DressCode and the test calls its RuleTester, so the project's own autoloader must
find DressCode: add it as a development dependency with composer require --dev dresscode/dresscode (installation says what that means for the project).
The Fixture First
Every rule in DressCode is developed and tested against fixtures: paired files containing code before and after an automated
fix. One fixture has up to three files: .code containing the input code, .expected containing the
expected output after the fix, and .violations listing the exact line numbers and messages the rule must report.
A fixture is the most unambiguous specification you can write, so we begin right there in
tests/fixtures/exceptionMessagePeriod/basic.code:
<?php
throw new InvalidArgumentException('The name must not be empty');
throw new \RuntimeException('Cannot connect to the database.');
throw new App\NotFoundException("Order $id not found");
throw new LogicException('Unreachable ');
$logger->log('Started');
Right here, we define the exact boundaries of what our rule should and shouldn't do: the message on line 3 needs the period;
the one on line 4 already has it; line 5 contains an interpolated string that we intentionally leave untouched (we can't predict
what $id will evaluate to); line 6 has trailing whitespace that the period should absorb; and line 7 isn't an
exception at all. The basic.expected file contains the exact same code with periods added on lines 3 and 6, while
basic.violations specifies the expected reports:
3: The message of an exception must end with a period.
6: The message of an exception must end with a period.
The Skeleton of the Rule
A rule is a class extending DressCode\NodeRule, decorated with the #[RuleInfo] attribute, which
among other things says in which stage (Stage) the rule runs. Our rule changes the code, not the whitespace, so it
belongs in the Structure stage; A Rule in
Detail describes the other stages.
A rule has no public name. In DressCode, users never configure or enable rules directly: they configure decisions
(configuration keys that define how code should look), and rules merely enforce them. Our decision is that exception messages must
end with a period. The rule declares this via getDecisions():
namespace App\CodeStyle;
use DressCode\Decision;
use DressCode\Domain;
use DressCode\NodeRule;
use DressCode\RuleContext;
use DressCode\RuleInfo;
use DressCode\Stage;
use PhpSyntax\Node;
use PhpSyntax\Nodes\Expression\NewNode;
use PhpSyntax\Token;
#[RuleInfo(Stage::Structure)]
final class ExceptionMessagePeriodRule extends NodeRule
{
public static function getDecisions(): array
{
return [
new Decision('project.exceptionMessagePeriod', Domain::state('required'), 'The message of an exception ends with a period'),
];
}
public function getVisitedNodes(): array
{
return [NewNode::class];
}
public function enter(Node|Token $node, RuleContext $context): void
{
}
}
A Decision consists of three parts. The path project.exceptionMessagePeriod connects
everything the user sees: they write it in their configuration, see it next to every finding in the terminal, use it in
dresscode:ignore comments, and query it using dresscode explain. Project-specific rules operate in the
project section, plugin rules use a section named after the plugin, and the engine uses its twenty or so built-in
sections, ensuring paths never collide. The domain Domain::state('required') defines accepted values: the
string required (“periods are mandatory”) and, like every decision that requires something, keep
(“do not check”). Finally, the description is an English sentence without a trailing period that explains what the rule
does where the key is not keep; it is displayed by dresscode explain and in the generated catalogue.
A decision like this is called a requirement: the rule runs wherever any configuration layer sets it to a value other
than keep. Where no configuration mentions it, it requires nothing and does not run. Rules are therefore never
enabled by class name: a project simply declares its desired code style, and the corresponding rule joins the run
automatically.
The syntax tree consists of nodes: each node is one construct of the code (a call, a condition, a class), and its parts
sit in its named slots. The getVisitedNodes() method declares which node types you want to inspect, and the
engine calls enter() exclusively for those nodes. We care about instantiation via new, represented by
NewNode, which has the slots newKeyword (the keyword new), class (the class
name) and arguments. The node reference lists all nodes and their
slots, and the glossary sums up the terms of
the tree.
Conditions and the Fix
Now for the core logic. In enter(), we evaluate a series of conditions against the syntax tree to detect
violations (adding imports for PhpSyntax\Nodes\NameNode and PhpSyntax\Nodes\Scalar\StringNode):
public function enter(Node|Token $node, RuleContext $context): void
{
if (
!$node instanceof NewNode
|| !$node->class instanceof NameNode
|| !str_ends_with($node->class->text, 'Exception')
) {
return;
}
$message = $node->arguments?->items->getItems()[0]->value ?? null;
if (
!$message instanceof StringNode
|| $message->quote !== "'"
|| $message->toValue() === ''
|| str_ends_with(rtrim($message->toValue()), '.')
|| !$context->report($message, 'The message of an exception must end with a period.')
) {
return;
}
$message->setValue(rtrim($message->toValue()) . '.');
}
Read the checks from the top down: this is a new instantiation with an explicit class name (not
new $class or an anonymous class), and the class name ends with Exception. The first argument is a plain
string without interpolation: an interpolated string in double quotes produces a completely different node, so line 5 of our
fixture is filtered out automatically without any special conditions. That string uses single quotes, is non-empty, and its
trimmed value doesn't already end with a period.
And the crucial final check: nobody suppressed the decision at this location. The $context->report()
method returns false if the construct is suppressed
by a dresscode:ignore comment on the same line or above it, or by a
dresscode:disable/dresscode:enable block. In that scenario, the code must not change. That is why
report() sits at the end of the if condition rather than before it. You don't need to pass the decision
path manually: a rule with a single requirement reports under it automatically.
Only after passing all these guards do we apply the fix: a single call to setValue(). We don't overwrite raw token
text; we update the string's semantic value, letting the node handle quotes and escaping automatically. The rest of the file
remains byte-for-byte identical.
Notice what this rule never has to deal with: no parenthesis counting, no hunting for argument boundaries, and no special
handling for inline comments nested inside the call. The syntax tree handles all of that. On a flat array of tokens, most of your
code would be spent defending against things that can appear between new and the string literal; in the tree, that
problem never arises.
Testing the Rule
Fixtures need to declare what value the decision runs with; otherwise it defaults to keep and the rule does
nothing. Configuration values for all fixtures in a directory belong in a values.neon file placed alongside them,
matching standard configuration syntax:
project:
exceptionMessagePeriod: required
The RuleTester utility takes the rule class and the fixtures directory and verifies that the output matches
.expected and the reported findings match .violations. It also checks everything you might otherwise
forget to test, for example that the rule changes nothing more on its own output and that no comment got lost; Testing Rules has the full list. Save the test next to the
fixtures directory, for example as tests/ExceptionMessagePeriodRule.phpt. In Nette Tester, it looks like this:
use App\CodeStyle\ExceptionMessagePeriodRule;
use DressCode\Testing\RuleTester;
use Tester\Assert;
require __DIR__ . '/../vendor/autoload.php';
Tester\Environment::setup();
Assert::noError(fn() => RuleTester::run(ExceptionMessagePeriodRule::class, __DIR__ . '/fixtures/exceptionMessagePeriod'));
The call is wrapped in Assert::noError() because Nette Tester expects at least one assertion per test; in PHPUnit,
you would place the same call inside a test method. You run the test like any other, in Nette Tester with
vendor/bin/tester tests.
Run the test now, and it will pass. If it fails, the diff reveals the exact line where the rule sees code differently than you
do. That is often when you discover subtle edge cases: in our case, rtrim() was missing in the first draft, and the
fixture with trailing whitespace immediately prompted its addition.
Enabling It in a Project
You can place your rule class anywhere your autoloader can find it. A good convention is placing custom rules in
tools/CodeStyle/ loaded via autoload-dev, preventing DressCode\NodeRule from entering your
production autoloader. In your configuration, register the rule class under rules, which adds its decisions to the
catalogue. Then configure its value in the project section, just like any built-in decision:
rules:
- App\CodeStyle\ExceptionMessagePeriodRule
project:
exceptionMessagePeriod: required
From this point on, dresscode check reports violations under its full path:
src/check.php error 8:39 The message of an exception must end with a period. project.exceptionMessagePeriod
The dresscode fix command repairs it automatically,
// dresscode:ignore project.exceptionMessagePeriod suppresses it locally, and
dresscode explain project.exceptionMessagePeriod displays its description, domain, and configuring layer, exactly
like any built-in engine decision. When multiple projects need the same rule, wrap it in a plugin; its decisions then simply relocate to the plugin's dedicated
section.
Where to Go Next
- When a rule needs additional values (such as a configurable list of exception name suffixes), it declares a parameter
alongside its requirement: a companion decision that refines behavior and is read in
configure(). See A Rule in Detail for how to do it, the domains, and everything a rule must follow. - Our rule identifies exceptions simply by checking if their name ends with
Exception. If you need more than that, use theNameResolveranalysis to resolve names against imports and namespaces; available analyses are documented in PhpSyntax. - Rules controlling spaces, indentation, and line breaks are written differently, submitting declarative claims instead of
implementing
enter(): Whitespace Rules. - If you are migrating an existing sniff from CodeSniffer or a fixer from PHP CS Fixer, check our porting guide: Porting a Rule from Another Tool.