Remove DowngradeGeneratedScalarTypesRector as way hacky to particular string solution, better use patching (#2289)

This commit is contained in:
Tomas Votruba 2022-05-11 19:21:59 +03:00 committed by GitHub
parent b8ff9ab25c
commit 9163864800
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 2 additions and 427 deletions

View File

@ -1,4 +1,4 @@
# 512 Rules Overview
# 511 Rules Overview
<br>
@ -28,7 +28,7 @@
- [DowngradePhp56](#downgradephp56) (5)
- [DowngradePhp70](#downgradephp70) (19)
- [DowngradePhp70](#downgradephp70) (18)
- [DowngradePhp71](#downgradephp71) (11)
@ -4221,27 +4221,6 @@ Replace the 2nd argument of `dirname()`
<br>
### DowngradeGeneratedScalarTypesRector
Refactor scalar types in PHP code in string snippets, e.g. generated container code from symfony/dependency-injection
- class: [`Rector\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector`](../rules/DowngradePhp70/Rector/String_/DowngradeGeneratedScalarTypesRector.php)
```diff
$code = <<<'EOF'
- public function getParameter(string $name)
+ /**
+ * @param string $name
+ */
+ public function getParameter($name)
{
return $name;
}
EOF;
```
<br>
### DowngradeInstanceofThrowableRector
Add `instanceof Exception` check as a fallback to `instanceof Throwable` to support exception hierarchies in PHP 5

View File

@ -21,7 +21,6 @@ use Rector\DowngradePhp70\Rector\MethodCall\DowngradeClosureCallRector;
use Rector\DowngradePhp70\Rector\MethodCall\DowngradeMethodCallOnCloneRector;
use Rector\DowngradePhp70\Rector\New_\DowngradeAnonymousClassRector;
use Rector\DowngradePhp70\Rector\Spaceship\DowngradeSpaceshipRector;
use Rector\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector;
use Rector\DowngradePhp70\Rector\TryCatch\DowngradeCatchThrowableRector;
return static function (RectorConfig $rectorConfig): void {
@ -41,7 +40,6 @@ return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(DowngradeUncallableValueCallToCallUserFuncRector::class);
$rectorConfig->rule(SplitGroupedUseImportsRector::class);
$rectorConfig->rule(DowngradeClosureCallRector::class);
$rectorConfig->rule(DowngradeGeneratedScalarTypesRector::class);
$rectorConfig->rule(DowngradeParentTypeDeclarationRector::class);
$rectorConfig->rule(DowngradeMethodCallOnCloneRector::class);
$rectorConfig->rule(DowngradeUnnecessarilyParenthesizedExpressionRector::class);

View File

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class DowngradeGeneratedScalarTypesRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
if ($this->isWindows()) {
$this->markTestSkipped('minor differences on windows, see https://github.com/rectorphp/rector/issues/6571');
}
$this->doTestFileInfo($fileInfo);
}
/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}
public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}

View File

@ -1,112 +0,0 @@
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
/**
* @return array|bool|float|int|string|null
*/
public function getParameter(string $name)
{
if (isset($this->buildParameters[$name])) {
return $this->buildParameters[$name];
}
if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters))) {
throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
}
if (isset($this->loadedDynamicParameters[$name])) {
return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
return $this->parameters[$name];
}
public function hasParameter(string $name): bool
{
if (isset($this->buildParameters[$name])) {
return true;
}
return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters);
}
public function setParameter(string $name, $value): void
{
throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
}
public function getParameterBag(): ParameterBagInterface
{
if (null === $this->parameterBag) {
$parameters = $this->parameters;
foreach ($this->loadedDynamicParameters as $name => $loaded) {
$parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
foreach ($this->buildParameters as $name => $value) {
$parameters[$name] = $value;
}
$this->parameterBag = new FrozenParameterBag($parameters);
}
return $this->parameterBag;
}
EOF;
?>
-----
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
/**
* @return array|bool|float|int|string|null
* @param string $name
*/
public function getParameter($name)
{
$name = (string) $name;
if (isset($this->buildParameters[$name])) {
return $this->buildParameters[$name];
}
if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters))) {
throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
}
if (isset($this->loadedDynamicParameters[$name])) {
return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
return $this->parameters[$name];
}
/**
* @param string $name
* @return bool
*/
public function hasParameter($name)
{
$name = (string) $name;
if (isset($this->buildParameters[$name])) {
return true;
}
return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters);
}
/**
* @param string $name
* @return void
*/
public function setParameter($name, $value)
{
$name = (string) $name;
throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
}
public function getParameterBag()
{
if (null === $this->parameterBag) {
$parameters = $this->parameters;
foreach ($this->loadedDynamicParameters as $name => $loaded) {
$parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
}
foreach ($this->buildParameters as $name => $value) {
$parameters[$name] = $value;
}
$this->parameterBag = new FrozenParameterBag($parameters);
}
return $this->parameterBag;
}
EOF;
?>

View File

@ -1,7 +0,0 @@
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
return $name;
EOF;

View File

@ -1,26 +0,0 @@
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
public function getParameter($name)
{
return $name;
}
EOF;
?>
-----
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
public function getParameter($name)
{
return $name;
}
EOF;
?>

View File

@ -1,30 +0,0 @@
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
public function getParameter(string $name)
{
return $name;
}
EOF;
?>
-----
<?php
namespace Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\Fixture;
$code = <<<'EOF'
/**
* @param string $name
*/
public function getParameter($name)
{
$name = (string) $name;
return $name;
}
EOF;
?>

View File

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\DowngradePhp70\Rector\FunctionLike\DowngradeScalarTypeDeclarationRector;
use Rector\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector;
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeDeclarationRector;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(DowngradeGeneratedScalarTypesRector::class);
// dependendent rules
$rectorConfig->rule(DowngradeScalarTypeDeclarationRector::class);
$rectorConfig->rule(DowngradeVoidTypeDeclarationRector::class);
};

View File

@ -1,174 +0,0 @@
<?php
declare(strict_types=1);
namespace Rector\DowngradePhp70\Rector\String_;
use Nette\Utils\Strings;
use PhpParser\Error;
use PhpParser\Node;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\NodeTraverser;
use Rector\Core\Contract\PhpParser\NodePrinterInterface;
use Rector\Core\Contract\Rector\PhpRectorInterface;
use Rector\Core\PhpParser\Parser\InlineCodeParser;
use Rector\Core\Rector\AbstractRector;
use Rector\DowngradePhp70\Rector\FunctionLike\DowngradeScalarTypeDeclarationRector;
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeDeclarationRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Testing\PHPUnit\StaticPHPUnitEnvironment;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Symplify\SmartFileSystem\SmartFileInfo;
/**
* @changelog https://github.com/symfony/symfony/blob/ad91659ea9b2a964f933bf27d0d1f1ef60fe9417/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1516
*
* @see \Rector\Tests\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector\DowngradeGeneratedScalarTypesRectorTest
*/
final class DowngradeGeneratedScalarTypesRector extends AbstractRector
{
/**
* Extends list here as needed
* @var string[]
*/
private const FILES_TO_INCLUDE = [
// https://github.com/symfony/symfony/blob/ad91659ea9b2a964f933bf27d0d1f1ef60fe9417/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1516
'vendor/symfony/dependency-injection/Dumper/PhpDumper.php',
];
/**
* @var PhpRectorInterface[]
*/
private array $phpRectors = [];
public function __construct(
private readonly InlineCodeParser $inlineCodeParser,
DowngradeScalarTypeDeclarationRector $downgradeScalarTypeDeclarationRector,
DowngradeVoidTypeDeclarationRector $downgradeVoidTypeDeclarationRector,
private readonly NodePrinterInterface $nodePrinter
) {
$this->phpRectors = [$downgradeScalarTypeDeclarationRector, $downgradeVoidTypeDeclarationRector];
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Refactor scalar types in PHP code in string snippets, e.g. generated container code from symfony/dependency-injection',
[
new CodeSample(
<<<'CODE_SAMPLE'
$code = <<<'EOF'
public function getParameter(string $name)
{
return $name;
}
EOF;
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$code = <<<'EOF'
/**
* @param string $name
*/
public function getParameter($name)
{
return $name;
}
EOF;
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [String_::class];
}
/**
* @param String_ $node
*/
public function refactor(Node $node): ?Node
{
$smartFileInfo = $this->file->getSmartFileInfo();
// this rule is parsing strings, so it heavy on performance; to lower it, we'll process only known opt-in files
if (! $this->isRelevantFileInfo($smartFileInfo)) {
return null;
}
$stringKind = $node->getAttribute(AttributeKey::KIND);
if (! in_array($stringKind, [String_::KIND_NOWDOC, String_::KIND_HEREDOC], true)) {
return null;
}
// we assume its a function list - see https://github.com/symfony/symfony/blob/ad91659ea9b2a964f933bf27d0d1f1ef60fe9417/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1513-L1560
try {
$nodes = $this->inlineCodeParser->parse('<?php class SomeClass { ' . $node->value . ' }');
} catch (Error) {
// nothing we can do
return null;
}
if ($nodes === []) {
return null;
}
// * replace scalar types with docs
// * remove return type
// somehow we want to call all Rector rules here
$nodeTraverser = $this->createNodeTraverser();
$changedNodes = $nodeTraverser->traverse($nodes);
if (! $changedNodes[0] instanceof Class_) {
return null;
}
$node->value = $this->printClassStmts($changedNodes[0]);
return $node;
}
private function isRelevantFileInfo(SmartFileInfo $fileInfo): bool
{
// for tests
if (StaticPHPUnitEnvironment::isPHPUnitRun()) {
return true;
}
foreach (self::FILES_TO_INCLUDE as $fileToInclude) {
if (\str_ends_with($fileInfo->getRealPath(), $fileToInclude)) {
return true;
}
}
return false;
}
private function printClassStmts(Class_ $class): string
{
$refactoredContent = '';
foreach ($class->stmts as $classStmt) {
$refactoredContent .= $this->nodePrinter->prettyPrint([$classStmt]) . PHP_EOL;
}
return $refactoredContent;
}
private function createNodeTraverser(): NodeTraverser
{
$nodeTraverser = new NodeTraverser();
foreach ($this->phpRectors as $phpRector) {
$nodeTraverser->addVisitor($phpRector);
}
return $nodeTraverser;
}
}