From 11337ce801c1b286c059b9df4d7c8fc0a29c2342 Mon Sep 17 00:00:00 2001 From: Michael Aherne Date: Tue, 2 Jul 2024 17:16:05 +0100 Subject: [PATCH] Fixes #174. Insert boilerplate correctly if there is a comment on first line. --- .../Sniffs/Files/BoilerplateCommentSniff.php | 13 +++++++++++-- moodle/Tests/FilesBoilerPlateCommentTest.php | 14 ++++++++++++++ .../boilerplatecomment/firstline_comment.php | 4 ++++ .../firstline_comment.php.fixed | 19 +++++++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 moodle/Tests/fixtures/files/boilerplatecomment/firstline_comment.php create mode 100644 moodle/Tests/fixtures/files/boilerplatecomment/firstline_comment.php.fixed diff --git a/moodle/Sniffs/Files/BoilerplateCommentSniff.php b/moodle/Sniffs/Files/BoilerplateCommentSniff.php index ab0f2ea..9eaed8c 100644 --- a/moodle/Sniffs/Files/BoilerplateCommentSniff.php +++ b/moodle/Sniffs/Files/BoilerplateCommentSniff.php @@ -233,8 +233,17 @@ private function fullComment(): array private function insertBoilerplate(File $file, int $stackptr): void { - $prefix = substr($file->getTokens()[$stackptr]['content'], -1) === "\n" ? '' : "\n"; - $file->fixer->addContent($stackptr, $prefix . implode("\n", $this->fullComment()) . "\n"); + $token = $file->getTokens()[$stackptr]; + $paddedComment = implode("\n", $this->fullComment()) . "\n"; + + if ($token['code'] === T_OPEN_TAG) { + $replacement = trim($token['content']) . "\n" . $paddedComment; + $file->fixer->replaceToken($stackptr, $replacement); + } else { + $prefix = substr($token['content'], -1) === "\n" ? '' : "\n"; + $file->fixer->addContent($stackptr, $prefix . $paddedComment); + } + } private function moveBoilerplate(File $file, int $start, int $target): void diff --git a/moodle/Tests/FilesBoilerPlateCommentTest.php b/moodle/Tests/FilesBoilerPlateCommentTest.php index a15016a..5beb600 100644 --- a/moodle/Tests/FilesBoilerPlateCommentTest.php +++ b/moodle/Tests/FilesBoilerPlateCommentTest.php @@ -212,4 +212,18 @@ public function testMoodleFilesBoilerplateCommentTrailingWhitespaceMissing() { $this->verifyCsResults(); } + + public function testMoodleFilesBoilerplateCommentFirstlineComment() { + $this->setStandard('moodle'); + $this->setSniff('moodle.Files.BoilerplateComment'); + $this->setFixture(__DIR__ . '/fixtures/files/boilerplatecomment/firstline_comment.php'); + + $this->setErrors([ + 1 => 'NoBoilerplateComment', + ]); + + $this->setWarnings([]); + + $this->verifyCsResults(); + } } diff --git a/moodle/Tests/fixtures/files/boilerplatecomment/firstline_comment.php b/moodle/Tests/fixtures/files/boilerplatecomment/firstline_comment.php new file mode 100644 index 0000000..e2915ff --- /dev/null +++ b/moodle/Tests/fixtures/files/boilerplatecomment/firstline_comment.php @@ -0,0 +1,4 @@ +. +// Some comment on first line. + +class test { +}