rector/rules/Php73/Rector/String_/SensitiveHereNowDocRector.php

80 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Php73\Rector\String_;
2018-10-17 01:47:21 +00:00
use PhpParser\Node;
use PhpParser\Node\Scalar\String_;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2018-10-17 07:54:48 +00:00
/**
2021-04-10 18:47:17 +00:00
* @changelog https://wiki.php.net/rfc/flexible_heredoc_nowdoc_syntaxes
* @see \Rector\Tests\Php73\Rector\String_\SensitiveHereNowDocRector\SensitiveHereNowDocRectorTest
2018-10-17 07:54:48 +00:00
*/
final class SensitiveHereNowDocRector extends AbstractRector implements MinPhpVersionInterface
2018-10-17 01:47:21 +00:00
{
/**
* @var string
*/
private const WRAP_SUFFIX = '_WRAP';
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::SENSITIVE_HERE_NOW_DOC;
}
public function getRuleDefinition() : RuleDefinition
2018-10-17 01:47:21 +00:00
{
return new RuleDefinition('Changes heredoc/nowdoc that contains closing word to safe wrapper name', [new CodeSample(<<<'CODE_SAMPLE'
$value = <<<A
2018-10-17 01:47:21 +00:00
A
A
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2018-10-17 01:47:21 +00:00
$value = <<<A_WRAP
A
A_WRAP
CODE_SAMPLE
)]);
2018-10-17 01:47:21 +00:00
}
/**
* @return array<class-string<Node>>
2018-10-17 01:47:21 +00:00
*/
public function getNodeTypes() : array
2018-10-17 01:47:21 +00:00
{
return [String_::class];
2018-10-17 01:47:21 +00:00
}
/**
* @param String_ $node
2018-10-17 01:47:21 +00:00
*/
public function refactor(Node $node) : ?Node
2018-10-17 01:47:21 +00:00
{
$kind = $node->getAttribute(AttributeKey::KIND);
if (!\in_array($kind, [String_::KIND_HEREDOC, String_::KIND_NOWDOC], \true)) {
2018-10-17 01:47:21 +00:00
return null;
}
// the doc label is not in the string → ok
/** @var string $docLabel */
$docLabel = $node->getAttribute(AttributeKey::DOC_LABEL);
if (\strpos($node->value, $docLabel) === \false) {
2018-10-17 01:47:21 +00:00
return null;
}
$node->setAttribute(AttributeKey::DOC_LABEL, $this->uniquateDocLabel($node->value, $docLabel));
2018-10-17 01:47:21 +00:00
// invoke redraw
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
2018-10-17 01:47:21 +00:00
return $node;
}
private function uniquateDocLabel(string $value, string $docLabel) : string
2018-10-17 01:47:21 +00:00
{
$docLabel .= self::WRAP_SUFFIX;
$docLabelCounterTemplate = $docLabel . '_%d';
$i = 0;
while (\strpos($value, $docLabel) !== \false) {
$docLabel = \sprintf($docLabelCounterTemplate, ++$i);
2018-10-17 01:47:21 +00:00
}
return $docLabel;
}
}