mirror of
https://github.com/rectorphp/rector.git
synced 2024-06-03 18:00:50 +00:00
f41cfb1de8
b4392749f4
Fix some code samples (#535)
77 lines
2.4 KiB
PHP
77 lines
2.4 KiB
PHP
<?php
|
|
|
|
declare (strict_types=1);
|
|
namespace Rector\DowngradePhp74\Rector\Property;
|
|
|
|
use PhpParser\Node;
|
|
use PhpParser\Node\NullableType;
|
|
use PhpParser\Node\Stmt\Property;
|
|
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
|
|
use Rector\Core\Rector\AbstractRector;
|
|
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
|
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
|
/**
|
|
* @see \Rector\Tests\DowngradePhp74\Rector\Property\DowngradeTypedPropertyRector\DowngradeTypedPropertyRectorTest
|
|
*/
|
|
final class DowngradeTypedPropertyRector extends \Rector\Core\Rector\AbstractRector
|
|
{
|
|
/**
|
|
* @var \Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger
|
|
*/
|
|
private $phpDocTypeChanger;
|
|
public function __construct(\Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger $phpDocTypeChanger)
|
|
{
|
|
$this->phpDocTypeChanger = $phpDocTypeChanger;
|
|
}
|
|
/**
|
|
* @return array<class-string<Node>>
|
|
*/
|
|
public function getNodeTypes() : array
|
|
{
|
|
return [\PhpParser\Node\Stmt\Property::class];
|
|
}
|
|
public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
|
|
{
|
|
return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes property type definition from type definitions to `@var` annotations.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
|
|
class SomeClass
|
|
{
|
|
private string $property;
|
|
}
|
|
CODE_SAMPLE
|
|
, <<<'CODE_SAMPLE'
|
|
class SomeClass
|
|
{
|
|
/**
|
|
* @var string
|
|
*/
|
|
private $property;
|
|
}
|
|
CODE_SAMPLE
|
|
)]);
|
|
}
|
|
/**
|
|
* @param Property $node
|
|
*/
|
|
public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
|
|
{
|
|
if ($node->type === null) {
|
|
return null;
|
|
}
|
|
if ($node->type instanceof \PhpParser\Node\NullableType) {
|
|
$node->props[0]->default = null;
|
|
}
|
|
$this->decoratePropertyWithDocBlock($node, $node->type);
|
|
$node->type = null;
|
|
return $node;
|
|
}
|
|
private function decoratePropertyWithDocBlock(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node $typeNode) : void
|
|
{
|
|
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
|
|
if ($phpDocInfo->getVarTagValueNode() !== null) {
|
|
return;
|
|
}
|
|
$newType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($typeNode);
|
|
$this->phpDocTypeChanger->changeVarType($phpDocInfo, $newType);
|
|
}
|
|
}
|