[CodingStyle] Skip re-escaping chars by SymplifyQuoteEscapeRector

This commit is contained in:
TomasVotruba 2019-12-30 12:13:17 +01:00
parent 83aebb7f77
commit 5858c7601f
2 changed files with 39 additions and 11 deletions

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Rector\CodingStyle\Rector\String_;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Scalar\String_;
use Rector\NodeTypeResolver\Node\AttributeKey;
@ -18,7 +19,7 @@ final class SymplifyQuoteEscapeRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Prefer quote that not inside the string', [
return new RectorDefinition('Prefer quote that are not inside the string', [
new CodeSample(
<<<'PHP'
class SomeClass
@ -62,21 +63,37 @@ PHP
$singleQuoteCount = substr_count($node->value, "'");
if ($node->getAttribute(AttributeKey::KIND) === String_::KIND_SINGLE_QUOTED) {
if ($doubleQuoteCount === 0 && $singleQuoteCount > 0) {
$node->setAttribute(AttributeKey::KIND, String_::KIND_DOUBLE_QUOTED);
// invoke override
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
$this->processSingleQuoted($node, $doubleQuoteCount, $singleQuoteCount);
}
if ($node->getAttribute(AttributeKey::KIND) === String_::KIND_DOUBLE_QUOTED) {
if ($singleQuoteCount === 0 && $doubleQuoteCount > 0) {
$node->setAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED);
// invoke override
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
$this->processDoubleQuoted($node, $singleQuoteCount, $doubleQuoteCount);
}
return $node;
}
private function processSingleQuoted(String_ $string, int $doubleQuoteCount, int $singleQuoteCount): void
{
if ($doubleQuoteCount === 0 && $singleQuoteCount > 0) {
// contains chars tha will be newly escaped
$matches = Strings::match($string->value, '#\\\\|\$#sim');
if ($matches) {
return;
}
$string->setAttribute(AttributeKey::KIND, String_::KIND_DOUBLE_QUOTED);
// invoke override
$string->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
}
private function processDoubleQuoted(String_ $string, int $singleQuoteCount, int $doubleQuoteCount): void
{
if ($singleQuoteCount === 0 && $doubleQuoteCount > 0) {
$string->setAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED);
// invoke override
$string->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace Rector\CodingStyle\Tests\Rector\String_\SymplifyQuoteEscapeRector\Fixture;
class SkipInversedOtherChars
{
public function run()
{
$name = 'Declaration of Kedlubna\extendTest::add($message) should be compatible with Kedlubna\test::add(string $message = \'\')';
}
}