Updated Rector to commit d54d8b18a92f4248605bc90b5af2b2a22c39a93e

d54d8b18a9 Hook NewInInitializerRector to a Class_ node (#4088)
This commit is contained in:
Tomas Votruba 2023-06-05 15:06:32 +00:00
parent 7b96363ba3
commit 63ba316fef
11 changed files with 137 additions and 117 deletions

View File

@ -7,6 +7,7 @@ use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Property;
use PHPStan\Type\MixedType;
use Rector\BetterPhpDocParser\PhpDoc\ArrayItemNode;
use Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode;
@ -137,7 +138,11 @@ CODE_SAMPLE
}
$attributeGroup = $this->phpAttributeGroupFactory->createFromClass(AttributeName::ATTRIBUTE);
$this->decorateTarget($phpDocInfo, $attributeGroup);
foreach ($node->getProperties() as $property) {
foreach ($node->stmts as $key => $stmt) {
if (!$stmt instanceof Property) {
continue;
}
$property = $stmt;
$propertyPhpDocInfo = $this->phpDocInfoFactory->createFromNode($property);
if (!$propertyPhpDocInfo instanceof PhpDocInfo) {
continue;
@ -154,7 +159,7 @@ CODE_SAMPLE
$propertyMetadata = new PropertyMetadata($propertyName, new MixedType(), Class_::MODIFIER_PUBLIC);
$this->propertyToAddCollector->addPropertyToClass($node, $propertyMetadata);
if ($this->shouldRemoveAnnotations) {
$this->removeNode($property);
unset($node->stmts[$key]);
}
}
$node->attrGroups[] = $attributeGroup;

View File

@ -0,0 +1,70 @@
<?php
declare (strict_types=1);
namespace Rector\Php81\NodeAnalyzer;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use Rector\NodeNameResolver\NodeNameResolver;
final class CoalesePropertyAssignMatcher
{
/**
* @readonly
* @var \Rector\Php81\NodeAnalyzer\ComplexNewAnalyzer
*/
private $complexNewAnalyzer;
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
private $nodeNameResolver;
public function __construct(\Rector\Php81\NodeAnalyzer\ComplexNewAnalyzer $complexNewAnalyzer, NodeNameResolver $nodeNameResolver)
{
$this->complexNewAnalyzer = $complexNewAnalyzer;
$this->nodeNameResolver = $nodeNameResolver;
}
/**
* Matches
*
* $this->value = $param ?? 'default';
*/
public function matchCoalesceAssignsToLocalPropertyNamed(Stmt $stmt, string $propertyName) : ?Coalesce
{
if (!$stmt instanceof Expression) {
return null;
}
if (!$stmt->expr instanceof Assign) {
return null;
}
$assign = $stmt->expr;
if (!$assign->expr instanceof Coalesce) {
return null;
}
$coalesce = $assign->expr;
if (!$coalesce->right instanceof New_) {
return null;
}
if ($this->complexNewAnalyzer->isDynamic($coalesce->right)) {
return null;
}
if (!$this->isLocalPropertyFetchNamed($assign->var, $propertyName)) {
return null;
}
return $assign->expr;
}
private function isLocalPropertyFetchNamed(Expr $expr, string $propertyName) : bool
{
if (!$expr instanceof PropertyFetch) {
return \false;
}
if (!$this->nodeNameResolver->isName($expr->var, 'this')) {
return \false;
}
return $this->nodeNameResolver->isName($expr->name, $propertyName);
}
}

View File

@ -4,15 +4,11 @@ declare (strict_types=1);
namespace Rector\Php81\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Property;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\Rector\AbstractRector;
@ -20,7 +16,7 @@ use Rector\Core\Reflection\ReflectionResolver;
use Rector\Core\ValueObject\MethodName;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\FamilyTree\NodeAnalyzer\ClassChildAnalyzer;
use Rector\Php81\NodeAnalyzer\ComplexNewAnalyzer;
use Rector\Php81\NodeAnalyzer\CoalesePropertyAssignMatcher;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -31,11 +27,6 @@ use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
*/
final class NewInInitializerRector extends AbstractRector implements MinPhpVersionInterface
{
/**
* @readonly
* @var \Rector\Php81\NodeAnalyzer\ComplexNewAnalyzer
*/
private $complexNewAnalyzer;
/**
* @readonly
* @var \Rector\Core\Reflection\ReflectionResolver
@ -46,11 +37,16 @@ final class NewInInitializerRector extends AbstractRector implements MinPhpVersi
* @var \Rector\FamilyTree\NodeAnalyzer\ClassChildAnalyzer
*/
private $classChildAnalyzer;
public function __construct(ComplexNewAnalyzer $complexNewAnalyzer, ReflectionResolver $reflectionResolver, ClassChildAnalyzer $classChildAnalyzer)
/**
* @readonly
* @var \Rector\Php81\NodeAnalyzer\CoalesePropertyAssignMatcher
*/
private $coalesePropertyAssignMatcher;
public function __construct(ReflectionResolver $reflectionResolver, ClassChildAnalyzer $classChildAnalyzer, CoalesePropertyAssignMatcher $coalesePropertyAssignMatcher)
{
$this->complexNewAnalyzer = $complexNewAnalyzer;
$this->reflectionResolver = $reflectionResolver;
$this->classChildAnalyzer = $classChildAnalyzer;
$this->coalesePropertyAssignMatcher = $coalesePropertyAssignMatcher;
}
public function getRuleDefinition() : RuleDefinition
{
@ -82,39 +78,40 @@ CODE_SAMPLE
*/
public function getNodeTypes() : array
{
return [ClassMethod::class];
return [Class_::class];
}
/**
* @param ClassMethod $node
* @param Class_ $node
*/
public function refactor(Node $node) : ?Node
{
$params = $this->resolveParams($node);
if ($node->stmts === null || $node->stmts === []) {
return null;
}
if ($node->isAbstract() || $node->isAnonymous()) {
return null;
}
$constructClassMethod = $node->getMethod(MethodName::CONSTRUCT);
if (!$constructClassMethod instanceof ClassMethod) {
return null;
}
$params = $this->resolveParams($constructClassMethod);
if ($params === []) {
return null;
}
$hasChanged = \false;
foreach ((array) $constructClassMethod->stmts as $key => $stmt) {
foreach ($params as $param) {
/** @var string $paramName */
$paramName = $this->getName($param->var);
$toPropertyAssigns = $this->betterNodeFinder->findClassMethodAssignsToLocalProperty($node, $paramName);
$toPropertyAssigns = \array_filter($toPropertyAssigns, static function (Assign $assign) : bool {
return $assign->expr instanceof Coalesce;
});
foreach ($toPropertyAssigns as $toPropertyAssign) {
/** @var Coalesce $coalesce */
$coalesce = $toPropertyAssign->expr;
if (!$coalesce->right instanceof New_) {
continue;
}
if ($this->complexNewAnalyzer->isDynamic($coalesce->right)) {
$paramName = $this->getName($param);
$coalesce = $this->coalesePropertyAssignMatcher->matchCoalesceAssignsToLocalPropertyNamed($stmt, $paramName);
if (!$coalesce instanceof Coalesce) {
continue;
}
/** @var NullableType $currentParamType */
$currentParamType = $param->type;
$param->type = $currentParamType->type;
$param->default = $coalesce->right;
$this->removeNode($toPropertyAssign);
unset($constructClassMethod->stmts[$key]);
$this->processPropertyPromotion($node, $param, $paramName);
$hasChanged = \true;
}
@ -133,9 +130,6 @@ CODE_SAMPLE
*/
private function resolveParams(ClassMethod $classMethod) : array
{
if (!$this->isLegalClass($classMethod)) {
return [];
}
$params = $this->matchConstructorParams($classMethod);
if ($params === []) {
return [];
@ -151,43 +145,28 @@ CODE_SAMPLE
$methodName = $this->nodeNameResolver->getName($classMethod);
return $classReflection instanceof ClassReflection && $this->classChildAnalyzer->hasAbstractParentClassMethod($classReflection, $methodName);
}
private function processPropertyPromotion(ClassMethod $classMethod, Param $param, string $paramName) : void
private function processPropertyPromotion(Class_ $class, Param $param, string $paramName) : void
{
$classLike = $this->betterNodeFinder->findParentType($classMethod, ClassLike::class);
if (!$classLike instanceof ClassLike) {
return;
foreach ($class->stmts as $key => $stmt) {
if (!$stmt instanceof Property) {
continue;
}
$property = $classLike->getProperty($paramName);
if (!$property instanceof Property) {
return;
$property = $stmt;
if (!$this->isName($stmt, $paramName)) {
continue;
}
$param->flags = $property->flags;
$param->attrGroups = \array_merge($property->attrGroups, $param->attrGroups);
$this->removeNode($property);
unset($class->stmts[$key]);
}
private function isLegalClass(ClassMethod $classMethod) : bool
{
$classLike = $this->betterNodeFinder->findParentType($classMethod, ClassLike::class);
if ($classLike instanceof Interface_) {
return \false;
}
if ($classLike instanceof Class_) {
return !$classLike->isAbstract();
}
return \true;
}
/**
* @return Param[]
*/
private function matchConstructorParams(ClassMethod $classMethod) : array
{
if (!$this->isName($classMethod, MethodName::CONSTRUCT)) {
return [];
}
if ($classMethod->params === []) {
return [];
}
if ((array) $classMethod->stmts === []) {
// skip empty constructor assigns, as we need those here
if ($classMethod->stmts === null || $classMethod->stmts === []) {
return [];
}
return \array_filter($classMethod->params, static function (Param $param) : bool {

View File

@ -19,12 +19,12 @@ final class VersionResolver
* @api
* @var string
*/
public const PACKAGE_VERSION = '408674025f7fc5295b5e67d7adaf11eca4dc1f24';
public const PACKAGE_VERSION = 'd54d8b18a92f4248605bc90b5af2b2a22c39a93e';
/**
* @api
* @var string
*/
public const RELEASE_DATE = '2023-06-05 14:37:14';
public const RELEASE_DATE = '2023-06-05 15:02:41';
/**
* @var int
*/

View File

@ -15,7 +15,7 @@ final class RectorKernel
/**
* @var string
*/
private const CACHE_KEY = 'v56';
private const CACHE_KEY = 'v57';
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface|null
*/

View File

@ -7,7 +7,6 @@ use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt;
@ -27,7 +26,6 @@ use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use PhpParser\Node\Stmt\While_;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface;
use Rector\Core\Exception\StopSearchException;
use Rector\Core\NodeAnalyzer\ClassAnalyzer;
@ -38,7 +36,6 @@ use Rector\Core\Util\MultiInstanceofChecker;
use Rector\Core\ValueObject\Application\File;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser;
use RectorPrefix202306\Webmozart\Assert\Assert;
/**
* @see \Rector\Core\Tests\PhpParser\Node\BetterNodeFinder\BetterNodeFinderTest
@ -70,24 +67,18 @@ final class BetterNodeFinder
* @var \Rector\Core\Util\MultiInstanceofChecker
*/
private $multiInstanceofChecker;
/**
* @readonly
* @var \Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser
*/
private $simpleCallableNodeTraverser;
/**
* @readonly
* @var \Rector\Core\Provider\CurrentFileProvider
*/
private $currentFileProvider;
public function __construct(NodeFinder $nodeFinder, NodeNameResolver $nodeNameResolver, NodeComparator $nodeComparator, ClassAnalyzer $classAnalyzer, MultiInstanceofChecker $multiInstanceofChecker, SimpleCallableNodeTraverser $simpleCallableNodeTraverser, CurrentFileProvider $currentFileProvider)
public function __construct(NodeFinder $nodeFinder, NodeNameResolver $nodeNameResolver, NodeComparator $nodeComparator, ClassAnalyzer $classAnalyzer, MultiInstanceofChecker $multiInstanceofChecker, CurrentFileProvider $currentFileProvider)
{
$this->nodeFinder = $nodeFinder;
$this->nodeNameResolver = $nodeNameResolver;
$this->nodeComparator = $nodeComparator;
$this->classAnalyzer = $classAnalyzer;
$this->multiInstanceofChecker = $multiInstanceofChecker;
$this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser;
$this->currentFileProvider = $currentFileProvider;
}
/**
@ -252,36 +243,6 @@ final class BetterNodeFinder
{
return $this->nodeFinder->findFirst($nodes, $filter);
}
/**
* @return Assign[]
*/
public function findClassMethodAssignsToLocalProperty(ClassMethod $classMethod, string $propertyName) : array
{
/** @var Assign[] $assigns */
$assigns = [];
$this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (Node $node) use($propertyName, &$assigns) {
// skip anonymous classes and inner function
if ($node instanceof Class_ || $node instanceof Function_) {
return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}
if (!$node instanceof Assign) {
return null;
}
if (!$node->var instanceof PropertyFetch) {
return null;
}
$propertyFetch = $node->var;
if (!$this->nodeNameResolver->isName($propertyFetch->var, 'this')) {
return null;
}
if (!$this->nodeNameResolver->isName($propertyFetch->name, $propertyName)) {
return null;
}
$assigns[] = $node;
return $node;
});
return $assigns;
}
/**
* @api symfony
* @return Assign|null

View File

@ -337,6 +337,9 @@ CODE_SAMPLE;
}
return $currentArgs;
}
/**
* @deprecated Return NodeTraverser::REMOVE_NODE or array of changed nodes instead
*/
protected function removeNode(Node $node) : void
{
$this->nodeRemover->removeNode($node);

2
vendor/autoload.php vendored
View File

@ -22,4 +22,4 @@ if (PHP_VERSION_ID < 50600) {
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit8b63bbf1bdfbd7bd5f442ea39ed30845::getLoader();
return ComposerAutoloaderInite0212492a03386f685dfdb847e331ea3::getLoader();

View File

@ -2262,6 +2262,7 @@ return array(
'Rector\\Php80\\ValueObject\\PropertyPromotionCandidate' => $baseDir . '/rules/Php80/ValueObject/PropertyPromotionCandidate.php',
'Rector\\Php80\\ValueObject\\StrStartsWith' => $baseDir . '/rules/Php80/ValueObject/StrStartsWith.php',
'Rector\\Php81\\Enum\\AttributeName' => $baseDir . '/rules/Php81/Enum/AttributeName.php',
'Rector\\Php81\\NodeAnalyzer\\CoalesePropertyAssignMatcher' => $baseDir . '/rules/Php81/NodeAnalyzer/CoalesePropertyAssignMatcher.php',
'Rector\\Php81\\NodeAnalyzer\\ComplexNewAnalyzer' => $baseDir . '/rules/Php81/NodeAnalyzer/ComplexNewAnalyzer.php',
'Rector\\Php81\\NodeAnalyzer\\EnumConstListClassDetector' => $baseDir . '/rules/Php81/NodeAnalyzer/EnumConstListClassDetector.php',
'Rector\\Php81\\NodeFactory\\EnumFactory' => $baseDir . '/rules/Php81/NodeFactory/EnumFactory.php',

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit8b63bbf1bdfbd7bd5f442ea39ed30845
class ComposerAutoloaderInite0212492a03386f685dfdb847e331ea3
{
private static $loader;
@ -22,17 +22,17 @@ class ComposerAutoloaderInit8b63bbf1bdfbd7bd5f442ea39ed30845
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit8b63bbf1bdfbd7bd5f442ea39ed30845', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInite0212492a03386f685dfdb847e331ea3', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit8b63bbf1bdfbd7bd5f442ea39ed30845', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInite0212492a03386f685dfdb847e331ea3', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInite0212492a03386f685dfdb847e331ea3::getInitializer($loader));
$loader->setClassMapAuthoritative(true);
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845::$files;
$filesToLoad = \Composer\Autoload\ComposerStaticInite0212492a03386f685dfdb847e331ea3::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;

View File

@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845
class ComposerStaticInite0212492a03386f685dfdb847e331ea3
{
public static $files = array (
'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php',
@ -2504,6 +2504,7 @@ class ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845
'Rector\\Php80\\ValueObject\\PropertyPromotionCandidate' => __DIR__ . '/../..' . '/rules/Php80/ValueObject/PropertyPromotionCandidate.php',
'Rector\\Php80\\ValueObject\\StrStartsWith' => __DIR__ . '/../..' . '/rules/Php80/ValueObject/StrStartsWith.php',
'Rector\\Php81\\Enum\\AttributeName' => __DIR__ . '/../..' . '/rules/Php81/Enum/AttributeName.php',
'Rector\\Php81\\NodeAnalyzer\\CoalesePropertyAssignMatcher' => __DIR__ . '/../..' . '/rules/Php81/NodeAnalyzer/CoalesePropertyAssignMatcher.php',
'Rector\\Php81\\NodeAnalyzer\\ComplexNewAnalyzer' => __DIR__ . '/../..' . '/rules/Php81/NodeAnalyzer/ComplexNewAnalyzer.php',
'Rector\\Php81\\NodeAnalyzer\\EnumConstListClassDetector' => __DIR__ . '/../..' . '/rules/Php81/NodeAnalyzer/EnumConstListClassDetector.php',
'Rector\\Php81\\NodeFactory\\EnumFactory' => __DIR__ . '/../..' . '/rules/Php81/NodeFactory/EnumFactory.php',
@ -3047,9 +3048,9 @@ class ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit8b63bbf1bdfbd7bd5f442ea39ed30845::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInite0212492a03386f685dfdb847e331ea3::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInite0212492a03386f685dfdb847e331ea3::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInite0212492a03386f685dfdb847e331ea3::$classMap;
}, null, ClassLoader::class);
}