File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed
Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 77use SavinMikhail \CommentsDensity \AnalyzeComments \Analyzer \DTO \Output \Report ;
88use SavinMikhail \CommentsDensity \AnalyzeComments \Config \DTO \Config ;
99
10+ /**
11+ * @see FileEditor to remove/update comments
12+ */
1013interface PluginInterface
1114{
1215 public function handle (Report $ report , Config $ config ): void ;
You can’t perform that action at this time.
0 commit comments