Skip to content

Commit

Permalink
fix: Strip left spaces from opening tags when comparing output for ch…
Browse files Browse the repository at this point in the history
…anges (#5701)

* fix: Strip left spaces from opening tags when comparing output for changes

Spaces removed from before opening tags in both the original and new content.

Fixes: rectorphp/rector#8533

* refactor: switched to ## delimiter for consistency

Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>

* refactor: when comparing trimmed existing and new content, check before regex first as it can be a little slower

* fix: when checking for changes, no need to ltrim the new content

---------

Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>
  • Loading branch information
stilliard and samsonasik committed Mar 10, 2024
1 parent e4b6ee6 commit bdc0907
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/Application/FileProcessor.php
Expand Up @@ -24,9 +24,16 @@
use Rector\ValueObject\Reporting\FileDiff;
use Symfony\Component\Console\Style\SymfonyStyle;
use Throwable;
use Nette\Utils\Strings;

final readonly class FileProcessor
{
/**
* @var string
* @see https://regex101.com/r/llm7XZ/1
*/
private const OPEN_TAG_SPACED_REGEX = '#^[ \t]+<\?php#m';

public function __construct(
private FormatPerservingPrinter $formatPerservingPrinter,
private RectorNodeTraverser $rectorNodeTraverser,
Expand Down Expand Up @@ -142,12 +149,17 @@ private function printFile(File $file, Configuration $configuration, string $fil
* Handle new line or space before <?php or InlineHTML node wiped on print format preserving
* On very first content level
*/
$originalFileContent = $file->getOriginalFileContent();
$ltrimOriginalFileContent = ltrim($originalFileContent);

$ltrimOriginalFileContent = ltrim($file->getOriginalFileContent());
if ($ltrimOriginalFileContent === $newContent) {
return;
}

// handle space before <?php
$ltrimNewContent = Strings::replace($newContent, self::OPEN_TAG_SPACED_REGEX, '<?php');
$ltrimOriginalFileContent = Strings::replace($ltrimOriginalFileContent, self::OPEN_TAG_SPACED_REGEX, '<?php');
if ($ltrimOriginalFileContent === $ltrimNewContent) {
return;
}
}

// change file content early to make $file->hasChanged() based on new content
Expand Down
@@ -0,0 +1,5 @@
<ul>
<?php if (true) { /* comment */ ?>
<li><a href="/test">test</a></li>
<?php } ?>
</ul>

0 comments on commit bdc0907

Please sign in to comment.