Skip to content

Commit

Permalink
[CodeQuality] Skip direct InlineHTML on CompleteMissingIfElseBracketR…
Browse files Browse the repository at this point in the history
…ector (#5125)

* [CodeQuality] Skip direct InlineHTML on CompleteMissingIfElseBracketRector

* Fixed 🎉

* [ci-review] Rector Rectify

* more example

* check end statement early

* Fixed 🎉

* more test

* [ci-review] Rector Rectify

* rename method

---------

Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
samsonasik and actions-user committed Oct 6, 2023
1 parent 96a1476 commit cd0881e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 22 deletions.
@@ -0,0 +1,5 @@
<div class="test <?php if (rand(0,1)) echo 'hidden'; ?>"></div>
-----
<div class="test <?php if (rand(0,1)) {
echo 'hidden';
} ?>"></div>
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\If_\CompleteMissingIfElseBracketRector\Fixture;

class SkipDirectHTML
{
public function run($value)
{
if ($value) ?>
<div>Hello</div>
<?php
}

public function run2($value)
{
if ($value) {

} elseif (rand(0, 1)) ?>

<div>Hello</div>

<?php
}

public function run3($value)
{
if ($value) {

} else ?>

<div>Hello</div>

<?php
}
}
Expand Up @@ -67,7 +67,7 @@ public function refactor(Node $node): ?Node
}

$oldTokens = $this->file->getOldTokens();
if ($this->isIfConditionFollowedByOpeningCurlyBracket($node, $oldTokens)) {
if ($this->shouldSkip($node, $oldTokens)) {
return null;
}

Expand All @@ -80,34 +80,18 @@ public function refactor(Node $node): ?Node
/**
* @param mixed[] $oldTokens
*/
private function isIfConditionFollowedByOpeningCurlyBracket(If_|ElseIf_|Else_ $if, array $oldTokens): bool
private function shouldSkip(If_|ElseIf_|Else_ $if, array $oldTokens): bool
{
for ($i = $if->getStartTokenPos(); $i < $if->getEndTokenPos(); ++$i) {
if ($oldTokens[$i] !== ')') {
if ($oldTokens[$i] === ';') {
// all good
return true;
}

continue;
}

// first closing bracket must be followed by curly opening brackets
// what is next token?
$nextToken = $oldTokens[$i + 1];

if (is_array($nextToken) && trim((string) $nextToken[1]) === '') {
// next token is whitespace
$nextToken = $oldTokens[$i + 2];
}

if (in_array($nextToken, ['{', ':'], true)) {
if ($oldTokens[$i] === ';') {
// all good
return true;
}
}

return false;
$startStmt = current($if->stmts);
$lastStmt = end($if->stmts);
return $startStmt === false || $lastStmt === false;
}

private function isBareNewNode(If_|ElseIf_|Else_ $if): bool
Expand Down

0 comments on commit cd0881e

Please sign in to comment.