Skip to content

Commit 6d105a0

Browse files
authored
[CodeQuality] Unwrap only percent-free string literal in UnwrapSprintfOneArgumentRector (#9018)
1 parent e42064a commit 6d105a0

4 files changed

Lines changed: 34 additions & 2 deletions

File tree

‎rules-tests/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector/Fixture/fixture.php.inc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Fixture
2222
public function run($var)
2323
{
2424
echo 'value';
25-
echo $var;
25+
echo sprintf($var);
2626
}
2727
}
2828

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\FuncCall\UnwrapSprintfOneArgumentRector\Fixture;
4+
5+
class SkipPercentLiteral
6+
{
7+
public function run()
8+
{
9+
echo sprintf('100%%');
10+
}
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\FuncCall\UnwrapSprintfOneArgumentRector\Fixture;
4+
5+
class SkipVariable
6+
{
7+
public function run($format)
8+
{
9+
echo sprintf($format);
10+
}
11+
}

‎rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PhpParser\Node;
88
use PhpParser\Node\Expr\FuncCall;
9+
use PhpParser\Node\Scalar\String_;
910
use Rector\Rector\AbstractRector;
1011
use Rector\RuleDoc\CodeSample\CodeSample;
1112
use Rector\RuleDoc\RuleDefinition;
@@ -51,7 +52,7 @@ public function refactor(Node $node): ?Node
5152
return null;
5253
}
5354

54-
if (count($node->getArgs()) > 1) {
55+
if (count($node->getArgs()) !== 1) {
5556
return null;
5657
}
5758

@@ -60,6 +61,15 @@ public function refactor(Node $node): ?Node
6061
return null;
6162
}
6263

64+
// only a literal without "%" prints itself, e.g. "%%" prints "%" and "%s" throws
65+
if (! $firstArg->value instanceof String_) {
66+
return null;
67+
}
68+
69+
if (str_contains($firstArg->value->value, '%')) {
70+
return null;
71+
}
72+
6373
return $firstArg->value;
6474
}
6575
}

0 commit comments

Comments
 (0)