Skip to content

Conversation

AronNovak
Copy link

@AronNovak AronNovak commented Aug 27, 2025

This PR adds a new PHPStan rule NoRedundantTraitUseRule that detects when a class uses traits redundantly - specifically when a class uses both a trait A and trait B, where trait A already uses trait B (either directly or transitively).

Motivation

This rule was initially developed for a Drupal project where it significantly improved PHPStan analysis performance by identifying and eliminating redundant trait usage.

This rule detects when a class uses traits redundantly - specifically when
a class uses both a trait A and trait B, where trait A already uses trait B
(either directly or transitively).

For example:
```php
trait BarTrait {
    public function bar() {}
}

trait FooTrait {
    use BarTrait;
    public function foo() {}
}

class MyClass {
    use FooTrait;
    use BarTrait; // Redundant! Already included via FooTrait
}
```

The rule helps improve code maintainability by:
- Reducing unnecessary trait usage
- Making trait dependencies clearer
- Potentially improving performance by reducing trait resolution overhead

Includes comprehensive test coverage for:
- Direct redundant trait usage
- Transitive redundant trait usage
- Valid non-redundant trait usage
- Single trait usage (no redundancy possible)
- Add Exception import statement instead of using fully qualified name
- Add missing newline at end of file
Add strict comparison parameter (true) to in_array() calls as required
by PHPStan strict rules configuration.
@AronNovak AronNovak changed the title Add NoRedundantTraitUseRule to detect redundant trait usage Add rule to detect redundant trait usage Aug 27, 2025
@mglaman
Copy link
Owner

mglaman commented Aug 27, 2025

My concern is that this isn't entirely specific to Drupal development and could be in its own package. I like the rule and wish PHPStan told me this already. I just don't know if it belongs here.

@AronNovak
Copy link
Author

@mglaman Thanks for the suggestion and the swift response.
phpstan/phpstan-strict-rules#279 - then we aim higher 😺

@AronNovak AronNovak closed this Aug 27, 2025
@AronNovak AronNovak deleted the add-no-redundant-trait-use-rule branch August 27, 2025 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants