Skip to content

Commit

Permalink
add fileeditor
Browse files Browse the repository at this point in the history
  • Loading branch information
savinmikhail committed Jan 8, 2025
1 parent 0112b4a commit a72ce59
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/AnalyzeComments/File/FileEditor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace SavinMikhail\CommentsDensity\AnalyzeComments\File;

use PhpToken;
use SavinMikhail\CommentsDensity\AnalyzeComments\Analyzer\DTO\Output\CommentDTO;
use SavinMikhail\CommentsDensity\AnalyzeComments\Exception\CommentsDensityException;

final readonly class FileEditor
{
public function updateCommentInFile(CommentDTO $comment): void
{
$fileContent = file_get_contents($comment->file);
$tokens = PhpToken::tokenize($fileContent);
$changed = false;
foreach ($tokens as $token) {
if ($token->line !== $comment->line) {
continue;
}
if (!$token->is([T_COMMENT, T_DOC_COMMENT])) {
continue;
}
$token->text = $comment->content;
$changed = true;
}
if (!$changed) {
return;
}
$this->save($comment->file, $tokens);
}

/**
* @param PhpToken[] $tokens
* @throws CommentsDensityException
*/
private function save(string $file, array $tokens): void
{
$content = implode('', array_map(static fn(PhpToken $token) => $token->text, $tokens));
$res = file_put_contents($file, $content);
if ($res === false) {
throw new CommentsDensityException('failed to write to file: ' . $file);
}
}
}
3 changes: 3 additions & 0 deletions src/Plugin/PluginInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
use SavinMikhail\CommentsDensity\AnalyzeComments\Analyzer\DTO\Output\Report;
use SavinMikhail\CommentsDensity\AnalyzeComments\Config\DTO\Config;

/**
* @see FileEditor to remove/update comments
*/
interface PluginInterface
{
public function handle(Report $report, Config $config): void;
Expand Down

0 comments on commit a72ce59

Please sign in to comment.