added failing ChangeIfElseValueAssignToEarlyReturnRector test, regarding lost comments (#4698)

This commit is contained in:
Markus Staab 2020-11-27 17:38:07 +01:00 committed by GitHub
parent 04abc7af5c
commit ae0d38e1f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 2 deletions

View File

@ -105,7 +105,9 @@ CODE_SAMPLE
/** @var Assign $assign */
$assign = $this->stmtsManipulator->getUnwrappedLastStmt($node->stmts);
$node->stmts[$lastIfStmtKey] = new Return_($assign->expr);
$return = new Return_($assign->expr);
$this->copyCommentIfExists($assign, $return);
$node->stmts[$lastIfStmtKey] = $return;
/** @var Assign $assign */
$assign = $this->stmtsManipulator->getUnwrappedLastStmt($node->else->stmts);
@ -113,7 +115,10 @@ CODE_SAMPLE
$lastElseStmtKey = array_key_last($node->else->stmts);
$elseStmts = $node->else->stmts;
$elseStmts[$lastElseStmtKey] = new Return_($assign->expr);
$return = new Return_($assign->expr);
$this->copyCommentIfExists($assign, $return);
$elseStmts[$lastElseStmtKey] = $return;
$node->else = null;
$this->addNodesAfterNode($elseStmts, $node);
@ -122,4 +127,10 @@ CODE_SAMPLE
return $node;
}
private function copyCommentIfExists(Node $from, Node $to): void
{
$nodeComments = $from->getAttribute(AttributeKey::COMMENTS);
$to->setAttribute(AttributeKey::COMMENTS, $nodeComments);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Rector\SOLID\Tests\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector\Fixture;
class LostComment
{
protected function replaceUrl($internalUrl, $publicUrl, $contenttext)
{
if (null === $publicUrl) {
// parameters could not be resolved into a url
$contenttext = preg_replace('@href=(["\'\s]*'.preg_quote($internalUrl, '@').'["\'\s]*)@', '', $contenttext);
} else {
// else comment
$contenttext = str_replace($internalUrl, $publicUrl, $contenttext);
}
return $contenttext;
}
}
?>
-----
<?php
namespace Rector\SOLID\Tests\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector\Fixture;
class LostComment
{
protected function replaceUrl($internalUrl, $publicUrl, $contenttext)
{
if (null === $publicUrl) {
// parameters could not be resolved into a url
return preg_replace('@href=(["\'\s]*'.preg_quote($internalUrl, '@').'["\'\s]*)@', '', $contenttext);
}
// else comment
return str_replace($internalUrl, $publicUrl, $contenttext);
}
}
?>