diff --git a/src/PhpParser/Printer/BetterStandardPrinter.php b/src/PhpParser/Printer/BetterStandardPrinter.php index fb1ab715d43..5e8dc11082b 100644 --- a/src/PhpParser/Printer/BetterStandardPrinter.php +++ b/src/PhpParser/Printer/BetterStandardPrinter.php @@ -26,7 +26,9 @@ use Rector\Comments\NodeDocBlock\DocBlockUpdater; use Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace; use Rector\Core\PhpParser\Printer\Whitespace\IndentCharacterDetector; +use Rector\Core\Provider\CurrentFileProvider; use Rector\Core\Util\StringUtils; +use Rector\Core\ValueObject\Application\File; use Rector\NodeTypeResolver\Node\AttributeKey; /** @@ -88,6 +90,7 @@ final class BetterStandardPrinter extends Standard public function __construct( private IndentCharacterDetector $indentCharacterDetector, private DocBlockUpdater $docBlockUpdater, + private CurrentFileProvider $currentFileProvider, array $options = [] ) { parent::__construct($options); @@ -116,8 +119,16 @@ public function printFormatPreserving(array $stmts, array $origStmts, array $ori // strip empty starting/ending php tags if (array_key_exists(0, $stmts) && $stmts[0] instanceof FileWithoutNamespace) { - $content = Strings::replace($content, self::EMPTY_STARTING_TAG_REGEX, ''); - $content = Strings::replace(\rtrim($content), self::EMPTY_ENDING_TAG_REGEX, '', ) ."\n"; + $originalContent = $content; + + $newContent = Strings::replace($content, self::EMPTY_STARTING_TAG_REGEX, ''); + $newContent = Strings::replace(\rtrim($newContent), self::EMPTY_ENDING_TAG_REGEX, '', ) ."\n"; + + if ($originalContent !== $newContent) { + /** @var File $file */ + $file = $this->currentFileProvider->getFile(); + return (string) file_get_contents($file->getFilePath()); + } } // add new line in case of added stmts diff --git a/src/ValueObjectFactory/ProcessResultFactory.php b/src/ValueObjectFactory/ProcessResultFactory.php index 0311cb689b8..a2418dd82ed 100644 --- a/src/ValueObjectFactory/ProcessResultFactory.php +++ b/src/ValueObjectFactory/ProcessResultFactory.php @@ -7,6 +7,7 @@ use Rector\Core\Application\FileSystem\RemovedAndAddedFilesCollector; use Rector\Core\ValueObject\Application\File; use Rector\Core\ValueObject\ProcessResult; +use Rector\Core\ValueObject\Reporting\FileDiff; use Rector\PostRector\Collector\NodesToRemoveCollector; final class ProcessResultFactory @@ -28,11 +29,16 @@ public function create(array $files): ProcessResult foreach ($files as $file) { $errors = array_merge($errors, $file->getErrors()); - if ($file->getFileDiff() === null) { + $fileDiff = $file->getFileDiff(); + if (!$fileDiff instanceof FileDiff) { continue; } - $fileDiffs[] = $file->getFileDiff(); + if ($fileDiff->getDiff() === '') { + continue; + } + + $fileDiffs[] = $fileDiff; } return new ProcessResult(