Imagine a class is a team of workers. If you have 5 workers and they all do simple tasks, the team is easy to manage. But if you have 5 workers and all of them are doing incredibly complex, multi-step math problems, the team is “heavy” and likely to make mistakes!
Weighted Methods per Class (WMC) looks at the complexity of your class as a whole.
We calculate the “Cyclomatic Complexity” (see E0009) for every single method in your class. Then, we add them all together!
If your total score is too high (default > 50), it means your class is doing too much heavy lifting. Even if no single method is terrible, the class overall is a nightmare to maintain.
This class has too many complex methods crammed into one place.
class ReportGenerator {
public function parseData(): void {
// ... 15 if statements and loops ...
}
public function validateData(): void {
// ... 12 if statements and loops ...
}
public function transformData(): void {
// ... 20 if statements and loops ...
}
public function exportData(): void {
// ... 10 if statements and loops ...
}
// Total WMC = 57 (Violation!)
}
Split the heavy lifting into smaller, specialized classes.
class ReportGenerator {
public function __construct(
private DataParser $parser,
private DataValidator $validator,
private DataTransformer $transformer,
private DataExporter $exporter
) {}
// WMC is now just 1! The heavy lifting is distributed.
public function generate(): void {
$data = $this->parser->parse();
$this->validator->validate($data);
$transformed = $this->transformer->transform($data);
$this->exporter->export($transformed);
}
}
rules:
E0018:
max_wmc: 50
If Phanalist flags your class for WMC, it means your class is a giant ball of logic. You need to take some of those heavy methods and move them into brand new classes.