Types from PHPStan
DressCode's lossless syntax tree understands every single space and comma in your codebase, but on its own it
cannot know that a variable named $form represents a form instance. When you have PHPStan installed in your project,
DressCode queries it directly. This unlocks capabilities a code style tool does not usually have: rewriting deprecated library
APIs based on what a variable actually is, inserting #[\Override] on methods overriding parents, and verifying that a
string literal safely matches an existing class name.
What the Tree Does Not Know
A rule inspecting the syntax tree in isolation sees a line accessing the constant $form::FILLED. But looking at a
single file, it has no way of knowing what $form holds at runtime. If it is a Nette form, whose class annotates that
constant with @deprecated use Form::Filled, the line should be rewritten. If it is any other object, the code must be
left completely untouched. An automated fix based on guesswork is far more dangerous than no fix at all.
Static analysis knows the exact answer, and you most likely already run it in your project via PHPStan. DressCode therefore
doesn't calculate types on its own. Instead, it queries your existing PHPStan installation, running with your project's
phpstan.neon and all your configured extensions. The answers are just as dependable as the static analysis you
already rely on every day, seamlessly understanding any framework-specific magic your extensions support.
Enabling the Types
Ideally, both PHPStan and DressCode belong directly in your project dependencies, ensuring DressCode consults the exact version of PHPStan and the configuration your team uses:
composer require --dev phpstan/phpstan dresscode/dresscode
Keep in mind that DressCode itself requires PHP 8.4 or newer to run, so your project must run on it too. The target PHP version your codebase is written for is a completely separate setting and can safely remain lower (see Installation). A project that does not run on PHP 8.4 installs both tools globally, as described below.
In your configuration, enabling type analysis takes a single line:
typeAnalysis: phpstan
That is all. The typeAnalysis key is a project fact (much like your target PHP version), and presets cannot enable
it on your behalf.
Do not confuse the key with the set types: the set says that you want type declarations actively written into your
code, while the typeAnalysis key says where DressCode learns about the types that already exist in it.
DressCode queries the PHPStan installed alongside it, that is, within the same vendor/ directory. When both are
installed in your project dependencies, as shown above, it communicates directly with your project's local PHPStan.
Alternatively, you can install both tools globally:
composer global require dresscode/dresscode phpstan/phpstan
A global PHPStan also understands your project's classes and dependencies without needing to load them: it reads structural
declarations directly from source files using composer.json and vendor/composer/installed.json. However,
analysis will run on the globally installed PHPStan version rather than the one locked in your project.
The PHPStan extensions stay those of your project, however DressCode is installed: it includes what your project's
phpstan/extension-installer registers and loads the classes of those extensions from your project's
vendor/ directory, as it does for an extension that phpstan.neon includes by a path into
vendor/. Extensions installed beside DressCode itself are not used. Extensions that require a booted runtime
environment (such as Larastan booting a Laravel application) will not function globally at all.
Installing DressCode via composer create-project includes PHPStan automatically, as it pulls in
DressCode's development dependencies. You then update PHPStan by running composer update inside that standalone
directory.
If you set typeAnalysis: phpstan but no PHPStan installation exists alongside DressCode (for instance, in a global
installation where PHPStan was omitted), DressCode issues a warning and proceeds without type analysis, exactly as if the key were
absent:
Warning: The configuration sets `typeAnalysis: phpstan`, but `phpstan/phpstan` is not installed beside DressCode, so the run goes without the types of the code. See https://dresscode.run/types#enable
However, if you explicitly configure a decision that strictly requires static types, that run will fail with a configuration
error, just as it would without the typeAnalysis key:
Error: Decision `upgrading.declarations.deprecatedMember` needs the types of the code, but `phpstan/phpstan` is not installed beside DressCode. See https://dresscode.run/types#enable
The dresscode upgrade today
command enables type analysis automatically, even without the key in the configuration. If it cannot find PHPStan alongside
itself, it refuses to run and halts immediately with an
error: The command needs the types of the code, but `phpstan/phpstan` is not installed beside DressCode.
Without PHPStan
Without the typeAnalysis key, DressCode functions normally; it simply omits decisions that require static types.
When those decisions come from a preset, a set or the upgrade data of a package, they are skipped quietly, allowing you to use
presets like nette (which contains several type-dependent decisions) even in codebases where PHPStan is absent.
Running dresscode config explains the reason beside each skipped decision:
classes: overridingMethod: parentCallOnly: forbidden # dresscode/cleanup, no effect: types ... hygiene: strlenEmptyTest: forbidden # dresscode/cleanup, no effect: types ... literals: classNameInString: forbidden # dresscode/cleanup, no effect: types
However, if you explicitly configure a type-dependent decision in your own configuration file, DressCode flags it as a configuration error. You requested behavior the engine cannot deliver, and running without it would falsely report that your code is clean:
Error: Decision `upgrading.declarations.deprecatedMember` needs the types of the code; set `typeAnalysis: phpstan` in the configuration and install `phpstan/phpstan` beside DressCode. See https://dresscode.run/types#enable
What You Gain
Take a presenter that uses deprecated Nette APIs and older conventions, checked with the following configuration:
use:
- nette
- deprecations
typeAnalysis: phpstan
upgrading:
classes:
Override: required
The message of each finding is in a comment on its line:
final class SignPresenter extends Presenter
{
protected function startup(): void // The method overriding `Nette\Application\UI\Presenter::startup()` must be marked with `#[\Override]`.
{
parent::startup();
$this->setLayout('sign');
}
protected function createComponentSignInForm(): Form
{
$form = new Form;
$form->addText('name')
->setAttribute('autofocus') // Method `Nette\Forms\Controls\BaseControl::setAttribute()` is deprecated: use setHtmlAttribute().
->addRule($form::FILLED, 'Enter your name'); // Constant `Nette\Forms\Form::FILLED` is deprecated: use Form::Filled.
return $form;
}
public function isAnonymous(string $name): bool
{
return strlen($name) === 0; // Useless `strlen()`, because `=== ''` says the same.
}
public function getRepositoryClass(): string
{
return 'App\Model\UserRepository'; // The class name must be written `App\Model\UserRepository::class` instead of a string.
}
}
And here is the file after running automated fixes:
final class SignPresenter extends Presenter
{
#[Override]
protected function startup(): void
{
parent::startup();
$this->setLayout('sign');
}
protected function createComponentSignInForm(): Form
{
$form = new Form;
$form->addText('name')
->setHtmlAttribute('autofocus')
->addRule($form::Filled, 'Enter your name');
return $form;
}
public function isAnonymous(string $name): bool
{
return $name === '';
}
public function getRepositoryClass(): string
{
return App\Model\UserRepository::class;
}
}
Every single one of these five findings required knowing something that cannot be deduced from the file's syntax alone. (That
#[\Override] became #[Override] is the work of the nette standard, which writes global
names without a leading backslash in a file without a namespace.)
- Deprecated APIs are updated by
upgrading.declarations.deprecatedMemberbased on@deprecatedannotations in library source code. Resolution is driven by the class that actually declares the constant or method rather than how it was invoked in code:$form::FILLEDis rewritten identically toForm::FILLED, and the message forsetAttribute()accurately cites theBaseControlclass even though it was called on a text input control. Deprecated classes are updated similarly viaupgrading.declarations.deprecatedClass. Most rewrites driven by the data of upgrade packages need types too, see How Upgrading Libraries Works. - The
#[\Override]attribute from PHP 8.3 is added byupgrading.classes.Override: requiredto any method that overrides a method in a parent class. PHP will then throw a compile-time fatal error if the parent ever renames that method, preventing your method from silently drifting into dead code. Implementations of abstract methods or interface contracts are intentionally skipped, as PHP already enforces those strictly without attributes. - Class names in string literals are safely converted to
::classsyntax byliterals.classNameInStringonly when a class, interface, or enum of that exact name genuinely exists in the project. IDEs will then reliably catch the reference during future refactorings. According to its own documentation, PHP CS Fixer'sclass_keywordrule cannot provide this safety because a token-based linter cannot know what classes exist across your project. - Empty string comparisons like
strlen($name) === 0are rewritten to$name === ''byhygiene.strlenEmptyTestonly when static analysis confirms that$nameis definitively a string. For any other type, the two constructs could behave differently.
Type information also powers classes.overridingMethod.parentCallOnly, which deletes boilerplate methods that do
nothing except pass arguments to the parent method of the same name. Static analysis verifies whether callers could tell the
difference: the parent must declare identical visibility, parameters, and return types. The fix is still risky, because a parent
method that reads func_get_args() would receive extra arguments once the method is gone; DressCode makes it once you
list the decision in the fixRisky key.
Decisions that safeguard inheritance contracts after upgrading libraries depend on types as well:
classes.overridingMethod.signature adapts a child method to a parent's updated signature,
mistakes.finalParent flags child classes extending a class that recently became final, and
mistakes.unimplementedAbstractMethod detects an abstract method the child does not implement. In the
dresscode/upgrade-nette package, nette.linkArguments and nette.monitorCallbacks rely on
types similarly.
Many other decisions run without types, but with them they safely fix what an unknown type would otherwise make risky:
| decision | what it learns from the types |
|---|---|
upgrading.functions.arraySearchFunctions |
that a loop goes over an array; a loop over an object is left alone |
expressions.comparison.loose, upgrading.syntax.match, mistakes.strictArgument |
that integers, booleans or enum cases are compared, where loose and strict comparison give the same result |
expressions.assignment.addingOne |
that the value is a number |
upgrading.functions.get_debug_type |
a string or an array |
expressions.assignment.targetInValue |
a plain property that ??= may leave unwritten |
expressions.coalesce |
a property or an array not accessed through magic methods |
upgrading.syntax.pipe |
that the method takes no parameter by reference; without types, the rewrite to the pipe operator is risky |
classes.staticMethod |
the real ancestor |
upgrading.api.attributeForMember, laravel.castsMethod, laravel.scopeAttribute |
also a class that inherits the parent indirectly, such as a model extending your own BaseModel; without types
only a class that names it in extends or implements |
upgrading.api.attributeForMember, upgrading.api.attributeForAnnotation |
an attribute whose constructor would miss a required argument; the first also an interface inherited from the parent, the second, with a namespace mask, a target class that does not exist or is not an attribute |
You don't need to enable type-dependent decisions individually: they are curated into the cleanup,
deprecations, and modernizations sets, and configuring typeAnalysis
automatically provides them with data. The nette standard already enforces code hygiene, so you only need to supply
the key and attach deprecations and modernizations (which are omitted from standards because upgrading
is a step you run when you choose):
typeAnalysis: phpstan
use:
- nette
- deprecations
- modernizations
With any other standard, you layer the sets alongside it:
typeAnalysis: phpstan
use:
- perCs
- cleanup
- deprecations
- modernizations
How They Work Together
DressCode never abandons its lossless syntax tree to obtain static types. It prints the tree to memory, lets PHPStan parse and analyze the code, and attaches each deduced type directly to its corresponding node based on source coordinates. Rules then query the node directly: What object is being called? Which method does this access target? What does its signature declare? PHPStan rewrites nothing and reports nothing; it acts as an oracle of facts. All actual refactoring and formatting is performed by DressCode, keeping all original indentation, whitespace, and comments intact.
This analysis involves overhead: every file passes through two separate parsers, and PHPStan must infer types. Running with
typeAnalysis: phpstan is therefore noticeably slower than a purely syntactic check. Results are cached, but with
types the cache saves time only when nothing in the project has changed since the last run.
The types of a file also depend on what the other files of the project declare. When a method in one of your classes gains a
@deprecated annotation, the files calling it do not change, yet they now have a finding. With types, the cache
fingerprint therefore holds the time and size of every file in the analyzed paths, phpstan.neon and the files PHPStan
loads from it, and the installed packages. As soon as any of them changes, the whole cache is thrown away. A verdict from the
cache thus stays true after a pull or a rebase, and you do not need --no-cache to get correct results. The price is
that after any edit of the code, the whole project is checked again.
In CI, the cache saves nothing with types, because a fresh checkout gives every file a new time. How to run the check with types in CI is described in Continuous Integration.
Where to Go Next
- Upgrading Code, where static type analysis powers automated rewrites during library updates.
- Upgrading to a Newer PHP, for modernizing language constructs to newer PHP releases.
- Configuration, how the
typeAnalysiskey interacts with presets and overrides.