Skip to content

Commit a72ce59

Browse files
committed
add fileeditor
1 parent 0112b4a commit a72ce59

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace SavinMikhail\CommentsDensity\AnalyzeComments\File;
4+
5+
use PhpToken;
6+
use SavinMikhail\CommentsDensity\AnalyzeComments\Analyzer\DTO\Output\CommentDTO;
7+
use SavinMikhail\CommentsDensity\AnalyzeComments\Exception\CommentsDensityException;
8+
9+
final readonly class FileEditor
10+
{
11+
public function updateCommentInFile(CommentDTO $comment): void
12+
{
13+
$fileContent = file_get_contents($comment->file);
14+
$tokens = PhpToken::tokenize($fileContent);
15+
$changed = false;
16+
foreach ($tokens as $token) {
17+
if ($token->line !== $comment->line) {
18+
continue;
19+
}
20+
if (!$token->is([T_COMMENT, T_DOC_COMMENT])) {
21+
continue;
22+
}
23+
$token->text = $comment->content;
24+
$changed = true;
25+
}
26+
if (!$changed) {
27+
return;
28+
}
29+
$this->save($comment->file, $tokens);
30+
}
31+
32+
/**
33+
* @param PhpToken[] $tokens
34+
* @throws CommentsDensityException
35+
*/
36+
private function save(string $file, array $tokens): void
37+
{
38+
$content = implode('', array_map(static fn(PhpToken $token) => $token->text, $tokens));
39+
$res = file_put_contents($file, $content);
40+
if ($res === false) {
41+
throw new CommentsDensityException('failed to write to file: ' . $file);
42+
}
43+
}
44+
}

src/Plugin/PluginInterface.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
use SavinMikhail\CommentsDensity\AnalyzeComments\Analyzer\DTO\Output\Report;
88
use SavinMikhail\CommentsDensity\AnalyzeComments\Config\DTO\Config;
99

10+
/**
11+
* @see FileEditor to remove/update comments
12+
*/
1013
interface PluginInterface
1114
{
1215
public function handle(Report $report, Config $config): void;

0 commit comments

Comments
 (0)