diff --git a/composer.json b/composer.json index 34ff3e33a..70e4208c0 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,6 @@ "ext-tokenizer": "*", "entropy/entropy": "^0.4.23", "nikic/php-parser": "^5.9", - "sebastian/lines-of-code": "^4.0", "webmozart/assert": "^2.4" }, "require-dev": { diff --git a/src/Lines/Analyser.php b/src/Lines/Analyser.php index 6f6b73be7..d6952e512 100644 --- a/src/Lines/Analyser.php +++ b/src/Lines/Analyser.php @@ -6,8 +6,8 @@ use PhpParser\NodeTraverser; use PhpParser\Parser; +use Rector\SwissKnife\Lines\NodeVisitor\CommentLineCountingNodeVisitor; use Rector\SwissKnife\Lines\NodeVisitor\StructureNodeVisitor; -use SebastianBergmann\LinesOfCode\Counter; use Throwable; use Webmozart\Assert\Assert; @@ -18,7 +18,6 @@ { public function __construct( private Parser $parser, - private Counter $counter, ) { } @@ -63,17 +62,16 @@ private function measureFile(Measurements $measurements, string $filePath): void $measurements->addFile($filePath); - // measure structure + // measure structure and comment lines in a single traversal + $commentLineCountingNodeVisitor = new CommentLineCountingNodeVisitor(); + $nodeTraverser = new NodeTraverser(); $nodeTraverser->addVisitor(new StructureNodeVisitor($measurements)); + $nodeTraverser->addVisitor($commentLineCountingNodeVisitor); $nodeTraverser->traverse($stmts); - // measure lines of code - $initLinesOfCode = $this->resolveInitLinesOfCode($fileContents); - $linesOfCode = $this->counter->countInAbstractSyntaxTree($initLinesOfCode, $stmts); - - $measurements->incrementLines($linesOfCode->linesOfCode()); - $measurements->incrementCommentLines($linesOfCode->commentLinesOfCode()); + $measurements->incrementLines($this->resolveInitLinesOfCode($fileContents)); + $measurements->incrementCommentLines($commentLineCountingNodeVisitor->getCommentLineCount()); } /** diff --git a/src/Lines/NodeVisitor/CommentLineCountingNodeVisitor.php b/src/Lines/NodeVisitor/CommentLineCountingNodeVisitor.php new file mode 100644 index 000000000..bd86c3f7c --- /dev/null +++ b/src/Lines/NodeVisitor/CommentLineCountingNodeVisitor.php @@ -0,0 +1,53 @@ +comments = array_merge($this->comments, $node->getComments()); + + return null; + } + + public function getCommentLineCount(): int + { + $commentLines = []; + + foreach ($this->uniqueComments() as $comment) { + for ($line = $comment->getStartLine(); $line <= $comment->getEndLine(); ++$line) { + $commentLines[$line] = true; + } + } + + return count($commentLines); + } + + /** + * @return Comment[] + */ + private function uniqueComments(): array + { + $uniqueComments = []; + + foreach ($this->comments as $comment) { + $key = $comment->getStartLine() . '_' . $comment->getStartTokenPos() + . '_' . $comment->getEndLine() . '_' . $comment->getEndTokenPos(); + $uniqueComments[$key] = $comment; + } + + return $uniqueComments; + } +}