-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0112b4a
commit a72ce59
Showing
2 changed files
with
47 additions
and
0 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
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); | ||
} | ||
} | ||
} |
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