-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor common logic into CommentMatcher (#28)
Co-authored-by: staabm <staabm@users.noreply.github.com>
- Loading branch information
Showing
3 changed files
with
52 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
<?php | ||
|
||
namespace staabm\PHPStanTodoBy\utils; | ||
|
||
use PhpParser\Comment; | ||
use PHPStan\Node\VirtualNode; | ||
use PhpParser\Node; | ||
|
||
final class CommentMatcher | ||
{ | ||
/** | ||
* @return iterable<Comment, array<mixed>> | ||
*/ | ||
public static function matchComments(Node $node, string $pattern): iterable | ||
{ | ||
if ( | ||
$node instanceof VirtualNode | ||
|| $node instanceof Node\Expr | ||
) { | ||
// prevent duplicate errors | ||
return []; | ||
} | ||
|
||
foreach ($node->getComments() as $comment) { | ||
|
||
$text = $comment->getText(); | ||
|
||
/** | ||
* PHP doc comments have the entire multi-line comment as the text. | ||
* Since this could potentially contain multiple "todo" comments, we need to check all lines. | ||
* This works for single line comments as well. | ||
* | ||
* PREG_OFFSET_CAPTURE: Track where each "todo" comment starts within the whole comment text. | ||
* PREG_SET_ORDER: Make each value of $matches be structured the same as if from preg_match(). | ||
*/ | ||
if ( | ||
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER) === false | ||
|| count($matches) === 0 | ||
) { | ||
continue; | ||
} | ||
|
||
yield $comment => $matches; | ||
} | ||
} | ||
} |