Repository navigation
Releases
Released Rector 2.9.3
Safer rules and smarter caching 🛡️
This release continues our effort towards safer and more reliable automated refactoring. More than 30 rules and internal analyzers now rely on native types where PHPDoc types alone cannot guarantee that a change preserves runtime behavior.
Caching also gets smarter: changes to parent classes, interfaces and traits now invalidate cached files that depend on them.
On top of that, we introduce a new dump-config command, Pest support, and switch to a new console framework.
New Features 🥳
- [DX] Add
dump-configcommand to print the resolved Rector configuration as JSON (#9071)
vendor/bin/rector dump-config-
[DX] Support
--configindump-config,list-rulesandvalidate-configcommands (#9103) -
[Php55] Extend
StringClassNameToClassConstantRectorto handle class method references, concatenated class method prefixes and references to the current class (#9066, #9068, #9069, #9070)
- $callback = 'App\Service\SomeService::run';
+ $callback = \App\Service\SomeService::class . '::run';-
[Renaming] Support case-insensitive class and constant name matching in
RenameClassRectorandRenameConstantRector(#9111, #9112) -
[Set] Add Pest support to composer-based sets (#9119, #9120)
return RectorConfig::configure()
->withComposerBased(pest: true);Smarter Caching ⚡
- Invalidate cached files when their parent class, interface or trait changes (#9090)
- Track traits used by parent classes and nested traits as file dependencies (#9092)
- Clear the cache before constructing rules when running with
--clear-cache, so cache entries created during rule initialization are preserved (#9085)
Native types over PHPDoc assumptions 🛡️
PHPDoc types are valuable for static analysis, but they do not necessarily reflect the actual runtime types.
More than 30 rules and internal analyzers have been hardened to use native types where relying on PHPDoc types could introduce unexpected behavior.
This affects rules across CodeQuality, CodingStyle, DeadCode, TypeDeclaration and PHP upgrade sets.
Among others:
- Keep necessary boolean casts in
UnnecessaryTernaryExpressionRector(#9134) - Avoid removing
instanceofassertions based solely on PHPDoc types inRemoveDeadInstanceOfAssertRector(#9124) - Keep conditions in
RemoveAlwaysTrueIfConditionRectorwhen their types are only guaranteed by PHPDoc (#9125) - Avoid removing potentially reachable loops in
RemoveDeadLoopRector(#9139) - Avoid declaring return types based on PHPDoc-only array shapes in
AddArrowFunctionReturnTypeRector(#9167) - Keep unused private method parameters when PHPDoc-only typed callers prevent safe removal (#9160, #9165)
The goal stays the same: prefer keeping code unchanged over making a potentially unsafe change.
Bugfixes 🐛
Core
- Fix missing scope for unreachable statements after labels (#8971)
- Fill scope on trait-level attribute arguments (#9091)
- Keep necessary skips when two skipped rules would perform the same change (#9072)
- Preserve tab indentation of reprinted nodes (#9087)
- Preserve heredoc content indentation in
BetterStandardPrinter(#9102) - Fix indentation of multiline method call arguments printed on a new line (#9117)
CodeQuality
- Handle constant definitions in
InlineIfToExplicitIfRector(#9078) - Skip floats in
SimplifyTautologyTernaryRector(#9084) - Use
||when converting negated multi-argumentisset()inIssetOnPropertyObjectToPropertyExistsRector(#9098)
DeadCode
- Preserve parentheses around cast expressions in
RecastingRemovalRector(#9094)
CodingStyle and TypeDeclaration
- [CodingStyle] Simplify shadowed function detection in
FunctionFirstClassCallableRector(#9067) - [CodingStyle] Skip consecutive static assignments of the same class in
NewlineBeforeNewAssignSetRector(#9118) - [TypeDeclaration] Skip non-array, possibly object and template types in
AddArrowFunctionParamArrayWhereDimFetchRector(#9073, #9074)
PHP sets
- [Php85] Skip increment, decrement, by-reference usage and other write contexts in
ArrayFirstLastRector(#9079, #9080, #9081) - [Php83] Skip
get_parent_class()in classes without a parent inRemoveGetClassGetParentClassNoArgsRector(#9101) - [Php81] Skip vendor MyCLabs enum method calls in
MyCLabsMethodCallToEnumConstRector(#9086, #9088) - [Php80] Preserve loose comparison behavior in
ChangeSwitchToMatchRector(#9065) - [Php74] Skip closures in constant expressions in
ClosureToArrowFunctionRector(#9097) - [Php71] Limit
BinaryOpBetweenNumberAndStringRectorto arithmetic and bitwise operators (#9114) - Preserve surrounding string content when converting backreferences in
PregReplaceEModifierRector(#9100) - Preserve the original
create_function()scope inCreateFunctionToAnonymousFunctionRector(#9099)
Developer Experience ✨
- Improve the deprecation message for per-version PHP sets registered through
withSets()(#9089) - Include
treatClassesAsFinal()andwithSymfonyContainerXml()configuration indump-configoutput (#9109, #9115) - Extend composer-based package detection for Symfony and Doctrine packages (#9093, #9110, #9113)
Removed 💀
- Remove deprecated
--rules-summaryoption (#9095) - Remove internal
SetList::PHP_POLYFILLSconstant (#9064)
Internals ⚙️
- Replace
symfony/consolewith theentropy/entropyconsole framework (#8787) - Bump PHP-Parser to 5.10 (#9082)
- Bump PHPStan to 2.4 (#9166)
- Bump PHPDoc Parser to 2.6 (#9168)
- Use
CallLike::getArg()for named and positional argument resolution across rules (#9075) - Restore static configuration parameters after
ConfigDumperTestto prevent test isolation issues (#9077)
Full Changelog: 2.9.2...2.9.3
Released Rector 2.9.2
Bugfixes 🐛
-
[CodeQuality] Remove
NarrowPreviousExceptionCodeArgRector, as it changesgetCode()of new exception to0(#9062), reported in #9061PHP does not inherit the code from the previous exception, so
new X('msg', previous: $e)returns0fromgetCode(), not$e->getCode(). The rule was part of thenamed-argsset and code quality level in 2.9.0. If you registered it manually, remove it from your config. -
[CodeQuality] Restore adding code with named
previous:argument inThrowWithPreviousExceptionRector(#9063)
Released Rector 2.9.0
Leaner rule set and safer rules 🧹
This release removes ~100 rules deprecated in past releases. They already threw on use, were part of no set and were rarely used. If your rector.php still registers one of them, remove it from the config. The goal stays the same: a smaller set of valuable, reliable rules for everyday upgrades.
The rest of the release is about safer changes - more than 30 rules now skip or keep code where the change could alter behavior: side effects, evaluation order, loose comparisons, fall-through cases, nullable types and more.
New Features 🥳
- [CodeQuality] Add
NarrowPreviousExceptionCodeArgRector, part of code-quality and named-args sets (#9052)
try {
$someCode = 1;
} catch (Throwable $throwable) {
- throw new \RuntimeException('ups', $throwable->getCode(), $throwable);
+ throw new \RuntimeException('ups', previous: $throwable);
}- [Php84] Handle property fetch, static access, array access and invocation on
NewMethodCallWithoutParenthesesRector(#9009, #9010) Thanks @alexndlm
-$message = (new Regex('some-pattern'))->message;
-$constant = (new Request())::METHOD_GET;
-$value = (new ArrayObject($items))['key'];
-$result = (new Invokable())();
+$message = new Regex('some-pattern')->message;
+$constant = new Request()::METHOD_GET;
+$value = new ArrayObject($items)['key'];
+$result = new Invokable()();- [Php71] Convert partial
list()destruct inListToArrayDestructRector(#9028)
-list(, $instanceId) = explode(':', $rate->id);
+[, $instanceId] = explode(':', $rate->id);- [TypeDeclaration] Allow
voidon final methods of non-final classes inAddVoidReturnTypeWhereNoReturnRector(#9051)
abstract class SomeClass
{
- final protected function run()
+ final protected function run(): void
{
echo 1;
}
}- [TypeDeclaration] Use
objectreturn type for(object)cast inReturnTypeFromReturnCastRector(#9021)
-public function run($data): \stdClass
+public function run($data): object
{
return (object) $data;
}- [CodeQuality] Drop redundant bool cast under negation in
UnnecessaryTernaryExpressionRector(#9024)
-return $order ? false : true;
+return !$order;- [dx] Report unnecessary skips in parallel runs too -
->reportUnusedSkips()now works with the default parallel run, not only with--debugorwithoutParallel()(#8957)
Bugfixes 🐛
Core
- Keep the narrowed scope of a ternary branch when a changed node is refreshed (#9007) Thanks @SanderMuller
- Fix class scope refresh skipping class attributes when class node is already in class (#9004) Thanks @APX403
- [Core] Skip classes unknown to reflection instead of crashing in
fetchClassLikeReflection()(#8965) Thanks @hmennen90 - [Caching] Fix removed skip not invalidating cache after
--clear-cacherun (#8934) - [Printer] Wrap compound assign on the left of
instanceofand binary ops (#9005) Thanks @odolbeau - [Php86] Handle crash on partial function application on PHP 8.6 scope set attribute (#9013)
DeadCode
- Keep side effects of assigned value in
RemoveUnusedPrivatePropertyRector(#9025) - Keep evaluation order of side effects and keep
clonestatement inRemoveDeadStmtRector(#9023, #9044) - Keep non-trailing constructor param in
RemoveUnusedPromotedPropertyRector(#9022) - Keep empty constructor of extendable class in
RemoveEmptyClassMethodRector(#9036) - Keep loops whose condition changes state in
RemoveDeadLoopRector(#9041) - Keep empty branch that guards later branches in
RemoveDeadIfBlockRector(#9042) - Skip case reached by fall-through in
RemoveDuplicatedCaseInSwitchRector(#9020) - Skip
BooleanAndin trait onRemoveAlwaysTrueIfConditionRector(#9003) Thanks @odolbeau - Keep
PHP_VERSION_IDcheck that can fail on the minimum version inRemovePhpVersionIdCheckRector(#9054) - Compare loosely on
==and!=inUnwrapFutureCompatibleIfPhpVersionRector(#9053)
CodeQuality
- Invert ordering comparisons only on int operands (#9059)
- Skip uninitialized typed array property in
SimplifyEmptyCheckOnEmptyArrayRector(#9060) - Check negated operand type in
BooleanNotIdenticalToNotIdenticalRector(#9043) - Keep original class name in
InlineIsAInstanceOfRector(#9032) - Skip self-assign result in
SimplifyBoolIdenticalTrueRector(#9029) - Keep loose comparison in
SingularSwitchToIfRector(#9019) - Unwrap only percent-free string literal in
UnwrapSprintfOneArgumentRector(#9018) - Preserve assignment parentheses in
NegatedAndsToPositiveOrsRector(#9011)
CodingStyle, TypeDeclaration, EarlyReturn, Privatization
- [CodingStyle] Keep string callable global when shadowed in
FunctionFirstClassCallableRector(#9057) - [CodingStyle] Require object in
ClosureFromCallableToFirstClassCallableRector(#9045) - [TypeDeclaration] Ignore docblock-narrowed args in
AddMethodCallBasedStrictParamTypeRector(#9048) - [EarlyReturn] Skip several ifs assigning the returned variable in
PreparedValueToEarlyReturnRector(#9033) - [Privatization] Fix invalid
private protected(set)on asymmetric visibility property onPrivatizeFinalClassPropertyRector(#8935)
PHP sets
- [Php86] Fold to
clamp()only when min <= max is proven inMinMaxToClampRector(#9058) - [Php85] Fix negative value on
ChrArgModuloRector(#8963) - [Php81] Skip array returned as array type in
ArrayToFirstClassCallableRector(#9035) - [Php80] Keep property type safe in
ClassPropertyAssignToConstructorPromotionRector(#9049) - [Php80] Skip int cast of string subject in
ChangeSwitchToMatchRector(#9056) - [Php80] Map empty operator to
<inVersionCompareFuncCallArgumentRector(#9055) - [Php73] Require non-empty array in
ArrayKeysToArrayKeyFirstLastRector(#9046) - [Php71/Php73] Skip call expression in
IsCountableRectorandIsIterableRector(#9038) - [Php70] Skip seeded files and unordered bounds in
RandomFunctionRector(#9016) - [Php70] Treat unescaped
{as literal inEregToPcreTransformer(#8964) Thanks @hmennen90
Removed 💀
Rules deprecated in 2.8 are now removed. Each already threw an exception on use.
- Remove ~100 deprecated rules across Arguments, Assert, CodeQuality, CodingStyle, DeadCode, EarlyReturn, Naming, Php70-Php85, Removing, Renaming, Strict, Transform, TypeDeclaration, TypeDeclarationDocblocks, Unambiguous and Visibility (#8937, #8938, #8939, #8940, #8941, #8942, #8943, #8944, #8945, #8946, #8947, #8948, #8949, [#8950](https://github.com/rectorphp/rector-src/pull...
Released Rector 2.8.5
Bugfixes and safer reprints 🐛
This release is mostly about bugfixes - an infinite loop fix in docblock return types, kept ternary parentheses on null coalescing, more precise changed_files in JSON output, and several new skips for dead code and PHP 8.4 rules. On the extension side, PHPUnit AddDoesNotPerformAssertionToNonAssertingTestRector is now faster and more precise.
Bugfixes 🐛
- [TypeDeclarationDocblocks] Skip invalid
@returntag to fix infinite loop inDocblockReturnArrayFromDirectArrayInstanceRector(#8918) - [ChangesReporting] List only changed files in JSON
changed_files(#8917) Thanks @gvieira18 - [Core] Drop file positions on reprinted nodes copied from another file (#8928)
- Preserve ternary fallback parentheses in new coalesces (#8927) Thanks @smotim
- [Php70] Keep inner ternary parentheses on
TernaryToNullCoalescingRector(#8921) - [Php55] Handle variable interpolated in pattern on
PregReplaceEModifierRector(#8922) - [Php84] Skip variable modified in condition on
ForeachToArrayAllRector,ForeachToArrayAnyRector,ForeachToArrayFindRectorandForeachToArrayFindKeyRector(#8925) - [DeadCode] Skip conditional return type on
RemoveUselessReturnTagRector(#8924) Thanks @APX403 - [DeadCode] Skip private methods used as callables on
RemoveUnusedPrivateMethodParameterRector(#8923) Thanks @phinor - [CodingStyle] Skip closure with rebound
$thisonArrowFunctionDelegatingCallToFirstClassCallableRectorandClosureDelegatingCallToFirstClassCallableRector(#8931)
Performance Improvements 🚀
- Remove usage of
CloningVisitoronAstResolver(#8861)
Internals ⚙️
- [Printer] Remove unneeded
BetterStandardPrinter::pStmt_FileNode()(#8904) - [CodingStyle] Cover Doctrine/Symfony aliased names on import names with real stubs (#8932, #8933)
rector-symfony 🎵
- [Symfony61] Do not add
#[AsCommand]without a name inCommandConfigureToAttributeRector(#1102) Thanks @kix - Skip first-class callable in
CommandConfigureToAttributeRector(#1104)
rector-phpunit 🟢
- [PHPUnit90] Handle named and unpacked
preg_match()args and skip non-literal expected value inAssertRegExpRector(#820, #819) Thanks @alies-dev - [PHPUnit100] Add
willReturnOnConsecutiveCalls()variables to closureuse()inWithConsecutiveRector(#821) - [PHPUnit120] Skip mocks configured through an alias in
ExpressionCreateMockToCreateStubRector(#823) Thanks @bbrala - [PHPUnit60] Follow
parent::test()calls inAddDoesNotPerformAssertionToNonAssertingTestRector(#826) Thanks @bbrala - [PHPUnit60] Count
expectUserDeprecationMessage()as assert, skip test methods in abstract classes and skip tests in classes with own asserting lifecycle methods inAddDoesNotPerformAssertionToNonAssertingTestRector(#825, #828, #831) - [PHPUnit60] Speed up
AddDoesNotPerformAssertionToNonAssertingTestRector- change node toClass_, cachecontainsAssertCall()per node and never parse PHPUnit and Symfony base test case methods (#830, #829, #833, #824)
rector-downgrade-php ⬇️
- Fix class constant spread from other class crash on
DowngradeArraySpreadRector(#423)
Released Rector 2.8.4
PHP 8.6 set additions and faster runs 🚀
This release grows the PHP 8.6 set with deprecated function alias renames, moves ConsistentImplodeRector down to the php74 set, and ships another round of performance work across the runner, printer, and reflection refresh.
New Features ⭐
- Add PHP 8.6 deprecated function alias renames to php86 set (#8905)
- Remove deprecated third arg of
define()in php86 set (#8906) - Move
ConsistentImplodeRectorfrom php80 to php74 (#8894) Thanks @zoliszabo
Bugfixes 🐛
- Run post rectors after the rules reach a fixed point, so no rule sees an imported short name (#8909) Thanks @SanderMuller
AnnotationToAttributeRector: fold unknown named args into the attribute's$options(#8914) Thanks @kix- [Php74] Fix
MbStrrposEncodingArgumentPositionRectortreating mixed$offsetas encoding (#8913) - [DeadCode] Skip nested conditional assign in
RemoveDefaultValueFromAssignedPropertyRector(#8915) - [DeadCode] Skip with HTML on
RemoveAlwaysTrueIfConditionRector(#8896) - [Printer] Keep blank lines between statements when a node list is emptied (#8886)
Performance Improvements 🚀
- Reduce double traversal on promoted property lookup in
AstResolver(#8903) - Reuse
File::containsHTML()onAddUseStatementGuardto cut a double traverse (#8899) - Reuse collected use statements when resolving PHPDoc short names (#8901)
- Skip current file lookup when a rule makes no change in
RectorRunner::run()(#8891) - Optimize class reflection refresh with cheaper cache hashing and early class-name validation (#8892)
- Skip
wrapBinaryOpWithBrackets()forCallLikenodes inBetterStandardPrinter::p()(#8890)
Internals ⚙️
- Convert Doctrine annotations from phpdoc-parser nodes, remove
StaticDoctrineAnnotationParser(#8881) Thanks @ondrejmirtes - Use PHPStan
Type::toNativePhpTypeNode()andType::toPhpDocNode()instead of own type mappers (#8885) Thanks @ondrejmirtes - Remove phpdoc-parser workarounds fixed in phpdoc-parser 2.3.10 and 2.3.11 (#8898) Thanks @ondrejmirtes
- Bump minimal phpstan and phpdoc-parser to latest patch versions (#8916)
- Make use of PHPStan
InClassNodeonPHPStanNodeScopeResolver(#8902) - [Core] Remove unneeded
origNodeattribute get onRectorRunner(#8893) - [Printer] Remove
BetterStandardPrinter::pExpr_Ternary()method (#8887) - [Printer] Remove
@propertyfor$insertionMaponBetterStandardPrinter(#8888)
Released Rector 2.8.3
Faster node traversal and updated PHPStan stack 🚀
This release brings performance improvements to node visitors, reducing unnecessary traversals and reflection resolution during analysis.
It also updates PHPStan to 2.3.4 and phpstan/phpdoc-parser to 2.4, with compatibility fixes for the updated PHPDoc type nodes.
Performance Improvements 🚀
- Avoid nested traversals in
ByRefNodeVisitorby tracking by-reference variable names perFunctionLike(#8879) Thanks @samsonasik - Only resolve call reflection for 2-item array arguments in
CallLikeReflectionNodeVisitor(#8880) Thanks @samsonasik
Bugfixes 🐛
- [TypeDeclaration]
AddArrayFunctionClosureParamTypeRector: resolve array item types from unions of arrays (#8877) Thanks @SanderMuller - Lock the fixture directory itself to prevent conflicts between parallel test workers using different
TMPDIRvalues (#8878) Thanks @SanderMuller
Internals ⚙️
- Bump PHPStan to 2.3.4 and
phpstan/phpdoc-parserto 2.4, adapting PHPDoc node handling for the newNameNode,FullyQualifiedNameNode, andRelativeNameNodetypes (#8883) Thanks @ondrejmirtes
Released Rector 2.8.2
Leaner PHPDoc stack and a fluent composer-based config 🚀
This release leans on phpstan/phpdoc-parser directly: Rector drops its own forked parser, printer, token iterator and type-node subclasses, and reuses the upstream parser, format-preserving printer, node traverser and type nodes. Fewer moving parts, one source of truth for PHPDoc handling, and it rides the PHPStan 2.3.3 bump. Thanks @ondrejmirtes.
On the config side, withComposerBased() now auto-detects installed packages when called with no argument, and a fluent withComposerBasedRule() builder lands across core and the rector-* sets.
New features 🥳
- Add
withComposerBasedRule()to the fluentRectorConfig::configure()builder (#8875) - [Configuration] Auto-detect installed packages in
withComposerBased()called with no argument (#8748) Thanks @MadBox-99 - [TypeDeclaration] Prefer same-namespace classes over global PHPDoc types (#8869) Thanks @MohannadElemary
- [dx] Report rule-scoped skips that matched a file but never changed it (#8853)
Performance Improvements 🚀
- Reduce memory usage on the LPT bucket by recycling workers and keeping files in discovery order (#8867) Thanks @samsonasik
- Cache skip-filtered rules per node class for the current file in
RectorRegistry::forNodeAndFile()(#8860) Thanks @samsonasik - Remove unneeded
array_values()when arrays are already lists or called too early (#8857) Thanks @samsonasik
Bugfixes 🐛
- [Php80]
TernaryToNullsafeCoalesceRector: fix a redundant nullsafe property access under coalesce (#8864) - [Php71]
BinaryOpBetweenNumberAndStringRector: skip an array dim fetch (#8862) - Resolve the item type of a union of arrays in
ArrayCallbackParamTypeResolver(#8874) Thanks @SanderMuller - Sort root files in
withRootFiles()to keep the cache hash stable (#8870) Thanks @M-arcus - Keep fixture lock files out of fixture directories (#8873) Thanks @localheinz
- Check the configuration cache only in the main process (#8851) Thanks @SanderMuller
- Restore
preload-split-package.phpto fix a PHPStan Turbo notice onrector-*packages (#8865) Thanks @samsonasik - Fix Windows CI tests under PHPStan Turbo (#8866, #8868) Thanks @samsonasik
Internals ⚙️
- Use the
phpstan/phpdoc-parserstack directly: parser without subclass, format-preserving printer,NodeTraverser, and move union dedup/array printing into type mappers (#8871, #8863, #8855, #8858) Thanks @ondrejmirtes - Remove the forked
BetterTokenIterator, theBracketsAwareIntersectionTypeNode, and type-node subclasses that only changed__toString()(#8856, #8876, #8872) Thanks @ondrejmirtes - Bump to PHPStan 2.3.3 and remove stale workarounds (#8859) Thanks @ondrejmirtes
- [cs] Apply the no-slash rule (#8852)
rector-doctrine 🟠
- Collapse an intersection with a single type, like a union (#541) Thanks @ondrejmirtes
- Use the fluent
withComposerBasedRule()in the composer-based set (#542)
rector-symfony 🎵
- Support converting
EventSubscriberInterfacetoAsEventListenerattributes (#1094) - Add
RequestQueryToMapQueryParameterRector(#1089) Thanks @Rajekevin - [Symfony34]
ContainerGetNameToTypeInTestsRector: skip when the FQCN service is not the named service (#1093) Thanks @jdreesen - Remove deprecated rules from the Rector
withSkip(#1096) - Use
PhpVersionconstants directly instead of the deprecatedPhpVersionFeature(#1095) - Use the new
Class_namespace forChangeMethodVisibilityRector(#1092) - Use the fluent
withComposerBasedRule()in the composer-based sets (#1098)
rector-phpunit 🟢
- Use
IntersectionTypeNodefromphpstan/phpdoc-parserand update fixtures for the new printer (#815, #814) Thanks @ondrejmirtes - Use the fluent
withComposerBasedRule()in the composer-based set (#816)
rector-downgrade-php ⬇️
- Update fixtures for the
phpstan/phpdoc-parserprinter, printing intersections without redundant brackets (#420) Thanks @ondrejmirtes
Released Rector 2.8.1
Fixes
- Fix crash cache due to PHPStan Turbo (#8850)
Released Rector 2.8
Faster runs, single-pass rules, and a leaner rule set 🚀
The Rector core engine is ~26 % faster (1.36x) with ~8 % less memory than 2.7.0.
If you run PHP 8.3+, it's 3x faster using PHPStan Turbo, the native parsing extension shipped with phpstan/phpstan:
| Rev | Core engine (time / peak RSS) |
|---|---|
| 2.7.0 | 32.0s / 351 MB |
| 2.8.0 | 23.6s / 324 MB |
| 2.8.0 + PHPStan Turbo (PHP 8.3+) | ~10.0s / ~317 MB |
Turbo factor measured on this release via an A/B run on Rector's own rules/ (24-core host, PHP 8.4, cold, identical changed-file fingerprint): ~2.4x wall and ~2.6x worker CPU. Turbo speeds up PHPStan parsing in the workers, so the wall-time gain scales with the available core count.
This release is mostly about speed and reliability. A large performance campaign hoists cheap node guards in front of expensive reflection, scope and type lookups across hundreds of rules, replaces per-node config scans in configurable rules with keyed lookups, and resolves short names and unused imports in a single AST walk.
Rules now converge in a single pass: instead of a re-processing guard, the engine iterates rules to a fixed point and tests enforce idempotency, so a rule that changes a file produces the same result whether it runs once or many times.
We also trimmed the rule set: many niche, context-dependent rules that are not part of any set and rarely used are now deprecated. Deprecated rules still run and print a warning; they will be removed in a future major release. The goal is a smaller set of valuable, reliable rules for everyday upgrades.
New features 🥳
- [CodeQuality] Add
ExplicitNullableObjectInstanceRector, replacing 4 nullable-object instanceof rules (#8636) - [Console] Add
--alloption tolist-rulesto list every rule in core andrector-*packages (#8637) - [Console] Undeprecate the
list-rulescommand (#8533) - Respect cgroup/CFS CPU quota when picking the parallel worker count (#8559)
- Bump to PHPStan 2.3
Performance Improvements 🚀
- Run the parallel workers with PHPStan Turbo, the native parsing extension shipped with
phpstan/phpstan, on PHP 8.3+ - no main-process restart, the workers do the analysis (#8812) Thanks @SanderMuller - Retarget class-level rules to a single
Class_/ClassLikenode and addgetClassReflection()toAbstractRector:RemoveParentDelegatingClassMethodRector,ReturnTypeFromMockObjectRector,AddVoidReturnTypeWhereNoReturnRectorandChangeMethodVisibilityRector(#8824, #8827, #8828, #8830, #8831) - Hoist the repeated fully qualified name build in
UseImportNameMatcher::resolveName()and resolve the parent class reflection by name inPhp4ConstructorRector(#8841, #8838) - Drop scope attachment on pre/post increment expressions and remove an unneeded
array_values()inBetterStandardPrinter::pArray()(#8814, #8821) - Hoist cheap name and structural guards before reflection, scope and type lookups across CodeQuality, DeadCode, CodingStyle, TypeDeclaration, Transform, EarlyReturn and legacy Php rules (#8664, #8666, #8667, #8668, #8669, #8670, #8671, #8672, #8661, #8663)
- Replace per-node config scans with keyed lookups in configurable rules - method, property, rename, transform, arguments and removing rules (#8734, #8735, #8736, #8739, #8742, #8743, #8744, #8745)
- Iterate rules to a fixed point with a content-cycle guard instead of a per-node re-processing guard, and enforce single-pass idempotency in tests (#8679, #8719, #8715, #8722)
- Skip rules whose work depends on a docblock when the node has none (#8624, #8625, #8626, #8627, #8628, #8629, #8630, #8631, #8632)
- Resolve short names and used names in a single AST walk, and cache resolved names per file version (#8697, #8700, #8701, #8702, #8704)
- Reuse the rebuilt
ClassReflectionby class content hash to stop memory growth on class refresh (#8731, #8728, #8729) - Cache per-file import facts in
ClassNameImportContext(#8687) - Cache
realpath()of skip patterns inFileInfoMatcher(#8699) Thanks @SanderMuller - Memoize
StaticPHPUnitEnvironment::isPHPUnitRunand replace theisStringNamewildcard loop with a singlestrpbrkscan (#8732, #8733) - Only process the catch statements PHPStan skipped and run the decorating visitors once (#8738)
- Avoid nested traversals in
ContextNodeVisitorby tracking loop/try/attribute depth (#8741) - Short-circuit
NodeComparator::areNodesEqualbefore printing (#8752) - Move skipping from
enterNode()toFileProcessorso it runs once per file (#8593) - Parallel LPT buckets for a more even worker load (#8496) Thanks @webard
- Add a single-process hotspot profiler and A/B benchmark script with a performance methodology (#8718, #8536)
- Speed up
ConvertStaticToSelfRector,ArrayToFirstClassCallableRectorandSimplifyEmptyCheckOnEmptyArrayRectorwith cheap guards before scope fetching (#8801, #8796, #8795) Thanks @alfredbez - Hoist loop-invariant resolve+continue guards above
foreach(#8761) - Stop attaching scope to class
extends/implementsnames and drop the unused process property on the node scope (#8788, #8792) - Remove the infinite-loop guard from
FileProcessornow that rules converge in a single pass (#8811)
Bugfixes 🐛
NewlineBeforeNewAssignSetRector: fix a false positive on a local var and$thisproperty name collision (#8535)SimplifyQuoteEscapeRector: handle strings with accented characters (#8532)TernaryToNullsafeCoalesceRector: skip mixed and untyped calls (#8531) Thanks @roxblnfkTernaryToNullCoalescingRector: preserve fallback parentheses on theIdentical/NotIdenticalpath (#8674)AddArrowFunctionReturnTypeRector: fix a crash onNonexistentParentClassType(#8568)- Fix scope on an enum when combining
DowngradeEnumToConstantListClassRectorandRenameMethodRector([#8727](https://github.com/rectorphp...
Released Rector 2.7
New Rules ✨
- Add
TernaryToNullsafeCoalesceRector(#8499) - Add
BoolReturnTypeFromBooleanConstAndStrictReturnsRectorfor mixed const + strict bool returns (#8498) - Add
ConstructorReadonlyAssignToDefaultRectorfor readonly property defaults (#8502) - Add
RemoveOverriddenAssignBeforeIfElseRector(#8505)
Performance Improvements 🚀
- Cache class-like name resolution per file version in
ShortNameResolver, so name import no longer rescans the whole file for every name - up to ~24 % fewer CPU instructions on large projects (#8524) - Cache dry-run files whose
FileDiffhas no content change (#8523) - Key the file cache on project-relative paths, so a cache survives a change of checkout (#8490)
- Use
FileSystem::writeAtomic()inFileCacheStorageto avoid partial cache reads on parallel runs (#8520) - Terminate timed-out and unconnected workers (#8522)
- Fix silently skipped files when the only worker is respawned (#8521)
- Give the worker the same NDJSON frame limit as the main process (#8489)
- Bump to PHPStan 2.3
Bugfixes 🐛
RenamePropertyRector: rename the property both in the trait and in the class property itself (#8518)RenameClassRector: throw on same old and new class in the configuration (#8515)ScalarParamTypeByMethodCallTypeRector: skip string param inference to avoid unsafe scalar coercion (#8514)RepeatedAndNotEqualToNotInArrayRector/RepeatedOrEqualToInArrayRector: skip short-circuit dependent values (#8516)SeparateMultiUseImportsRector: keep traituseadaptations (#8510)Privatize*Rector: drop thefinalflag when changingprotectedtoprivate, sinceprivate finalis forbidden on PHP 8.4 (#8509)AddNameToBooleanArgumentRector/AddNameToNullArgumentRector: skip callees marked@no-named-arguments(#8508)TypedPropertyFromStrictConstructorRector: skip a protected property redeclared in a child class (#8503)RemoveAlwaysTrueIfConditionRector: skip a maybe-undefined variable (#8501)SingularSwitchToIfRector: skip nestedbreak/continuein the case body (#8500)TypeDeclaration: skip redundant intersection types in union return types (#8527)- Naming: keep mass nouns ending in
data/infountouched when singularizing (#8492)
rector-doctrine 🟠
- Add
DoctrineQueryBuilderSortDirectionRector(#524) - Add
DoctrineOrderByAttributeSortDirectionRector(#525) - Register the SortDirection rules in the composer-based set and cover
Expr\OrderBy::add()(#530) CorrectDefaultTypesOnEntityPropertyRector: support properties initialized asint(#526)
rector-symfony 🎵
GetRequestRector: reuse an existing untyped$requestparam (#1066)CommandConfigureToAttributeRector: do not report a change when nothing is extracted (#1068)- Fix
PhpAstExtractorimport removal in the composer-based Symfony set (#1070)
rector-phpunit 🟢
- Add
WillReturnCallbackFallbackToReturnFalseRector(#784) - Extend
FlipAssertRectorto more assert methods and expected value shapes (#787) AllowMockObjectsForDataProviderRector: skip stub-only->method()calls (#790)- Fix changing keys of data providers for tests with optional arguments (#783)
- Deprecate
ConfiguredMockEntityToSetterObjectRectoras experimental (#789)