/** * Called once after traversal. * * Return value semantics: * * null: $nodes stays as-is * * otherwise: $nodes is set to the return value * * @param Node[] $nodes Array of nodes * * @return null|Node[] Array of nodes */ public function afterTraverse(array $nodes) { if ($this->namespace == '') { $this->result->error(ErrorType::MISSING_NAMESPACE, null, 'Every source file should have a namespace'); } $autoFix = $this->result->getConfig()->autoFix; $useStatementOrganizer = new UseStatementOrganizer($this->useStatements); $lineNumberMovements = []; if (!$useStatementOrganizer->areOrganized()) { $errorMsg = "Uses are not organized"; if ($autoFix) { $lineSwaps = $useStatementOrganizer->getLineSwaps(); $lineNumberMovements = $useStatementOrganizer->getLineNumberMovements(); foreach ($lineSwaps as $currentLine => $newLine) { $fix = new SwapLineFix($currentLine, $newLine, $errorMsg); $this->result->fix($fix); } } else { $lineSwaps = $useStatementOrganizer->getLineSwaps(); foreach ($lineSwaps as $currentLine => $newLine) { $this->result->error(ErrorType::DISORGANIZED_USES, $currentLine, $errorMsg . ": this use should be on {$newLine}"); } } } $unusedFixes = []; foreach ($this->aliases as $use) { $errorMsg = ''; $name = $use->getName(); if ($use->getUseCount() == 0) { $errorMsg = "Use '{$name}' is not being used"; } elseif (str_replace("{$this->namespace}\\", '', "\\{$name}") === $use->getAlias()) { $errorMsg = "Use '{$name}' is automatically included as it is in the same namespace"; } if ($errorMsg) { if ($autoFix) { $line = $use->getNode()->getLine(); // if organization occurred the line may have moved if (isset($lineNumberMovements[$line])) { $line = $lineNumberMovements[$line]; } $fix = new RemoveLineFix($line, $errorMsg); $unusedFixes[$line] = $fix; } else { $this->result->error(ErrorType::UNUSED_USE, $use->getNode()->getLine(), $errorMsg); } } } if ($autoFix) { // removing must be done in reverse order krsort($unusedFixes); foreach ($unusedFixes as $fix) { $this->result->fix($fix); } } }
/** * @expectedException \BadMethodCallException */ public function testGetLineNumberMappingWithoutLineSwap() { $useStatementOrganizer = new UseStatementOrganizer([]); $useStatementOrganizer->getLineNumberMovements(); }