Part of #3641170: [meta] Call parent constructor instead of duplicating property assignment.
Problem/Motivation
#3635402: Promote remaining properties in constructors and add @param docs where needed flagged up that we have several classes in core where instead of calling the parent constructor, the class assigns the property itself. For property promotion, it would be better to call the parent constructor (which can then do property promotion). This will also make it easier to handle adding readonly.
Proposed resolution
Per #3641170-9: [meta] Call parent constructor instead of duplicating property assignment, in this issue introduce a custom PHPStan rule to identify the places where constructor parameters are assigned to properties in the body of the constructor.
Baseline the new errors.
In follow-ups, fix the constructors, promoting parameters where appropriate, passing parameters to the parent constructors, adjusting the parent constructors, etc.
Assumptions
The rule is based on a few deliberate assumptions:
- Direct assignment: it ONLY looks for constructor statements that assign a constructor parameter directly to a property using
$this->property = $parameter, outside of any possible loop or conditional code block. - Property ownership: it reports assignments regardless of whether the property is declared in the current class or inherited from a parent class.
- Refactoring is not automatic: the appropriate solution could be constructor property promotion, calling the parent constructor, or even a refactoring of the parent constructor. Each case needs evaluation.
What the rule does
The rule reports constructor parameters that are directly assigned to class properties.
For example:
class Example {
protected SomeService $property;
public function __construct(SomeService $parameter) {
$this->property = $parameter;
}
}
It reports this pattern because the parameter could potentially be promoted:
class Example {
public function __construct(
protected SomeService $property,
) {
}
}Remaining tasks
User interface changes
Introduced terminology
API changes
Data model changes
Release notes snippet
Disclaimer: LLM was used to build an initial draft of the rule, and to summarise its design to add it to the proposed resolution section here.
Issue fork drupal-3641651
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #3
mondrakeAdded rule test (LLM assisted)