-
Notifications
You must be signed in to change notification settings - Fork 88
Add a @use annotation to HasFactory trait usages #374
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
imliam
wants to merge
10
commits into
driftingly:main
Choose a base branch
from
imliam:rector-factory-docblock
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c3ccbba
Add a use annotation to HasFactory trait usages
imliam b3d6752
Update to check the factory actually exists before applying the annot…
imliam 36d8028
Merge branch 'main' into rector-factory-docblock
driftingly 83f512d
Refactor to UsesTagValueNode
imliam 8754876
Remove redundant trait name check
imliam 883bfde
Update files to correct directory/namespace
imliam 5e7dc1b
Make rule configurable
imliam 59ca54a
Run `composer docs` to update documentation
imliam 9c89d28
If factory property exists, use that
imliam b21be64
Code style fixes
imliam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
285 changes: 285 additions & 0 deletions
285
src/Rector/Class_/AddUseAnnotationToHasFactoryTraitRector.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,285 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace RectorLaravel\Rector\Class_; | ||
|
|
||
| use PhpParser\Node; | ||
| use PhpParser\Node\Expr\ClassConstFetch; | ||
| use PhpParser\Node\Scalar\String_; | ||
| use PhpParser\Node\Stmt\Class_; | ||
| use PhpParser\Node\Stmt\Property; | ||
| use PhpParser\Node\Stmt\TraitUse; | ||
| use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode; | ||
| use PHPStan\PhpDocParser\Ast\PhpDoc\UsesTagValueNode; | ||
| use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; | ||
| use PHPStan\Reflection\ReflectionProvider; | ||
| use PHPStan\Type\ObjectType; | ||
| use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory; | ||
| use Rector\BetterPhpDocParser\ValueObject\Type\FullyQualifiedIdentifierTypeNode; | ||
| use Rector\Comments\NodeDocBlock\DocBlockUpdater; | ||
| use Rector\Contract\Rector\ConfigurableRectorInterface; | ||
| use RectorLaravel\AbstractRector; | ||
| use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample; | ||
| use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; | ||
| use Webmozart\Assert\Assert; | ||
|
|
||
| /** | ||
| * @see \RectorLaravel\Tests\Rector\Class_\AddUseAnnotationToHasFactoryTraitRector\AddUseAnnotationToHasFactoryTraitRectorTest | ||
| */ | ||
| final class AddUseAnnotationToHasFactoryTraitRector extends AbstractRector implements ConfigurableRectorInterface | ||
| { | ||
| public const string FACTORY_NAMESPACES = 'factoryNamespaces'; | ||
|
|
||
| private const string USE_TAG_NAME = '@use'; | ||
|
|
||
| private const string HAS_FACTORY_TRAIT = 'Illuminate\Database\Eloquent\Factories\HasFactory'; | ||
|
|
||
| /** | ||
| * @var string[] | ||
| */ | ||
| private array $factoryNamespaces = ['Database\\Factories']; | ||
|
|
||
| public function __construct( | ||
| private readonly DocBlockUpdater $docBlockUpdater, | ||
| private readonly PhpDocInfoFactory $phpDocInfoFactory, | ||
| private readonly ReflectionProvider $reflectionProvider, | ||
| ) {} | ||
|
|
||
| public function getRuleDefinition(): RuleDefinition | ||
| { | ||
| return new RuleDefinition( | ||
| 'Adds @use annotation to HasFactory trait usage to provide better IDE support.', | ||
| [new ConfiguredCodeSample( | ||
| <<<'CODE_SAMPLE' | ||
| use Illuminate\Database\Eloquent\Model; | ||
| use Illuminate\Database\Eloquent\Factories\HasFactory; | ||
|
|
||
| class User extends Model | ||
| { | ||
| use HasFactory; | ||
| } | ||
| CODE_SAMPLE, | ||
| <<<'CODE_SAMPLE' | ||
| use Illuminate\Database\Eloquent\Model; | ||
| use Illuminate\Database\Eloquent\Factories\HasFactory; | ||
|
|
||
| class User extends Model | ||
| { | ||
| /** @use \Illuminate\Database\Eloquent\Factories\HasFactory<\Database\Factories\UserFactory> */ | ||
| use HasFactory; | ||
| } | ||
| CODE_SAMPLE, | ||
| [self::FACTORY_NAMESPACES => ['Database\\Factories']] | ||
| )] | ||
| ); | ||
| } | ||
|
|
||
| public function configure(array $configuration): void | ||
| { | ||
| if ($configuration === []) { | ||
| $this->factoryNamespaces = ['Database\\Factories']; | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| Assert::keyExists($configuration, self::FACTORY_NAMESPACES); | ||
| Assert::isArray($configuration[self::FACTORY_NAMESPACES]); | ||
| Assert::allString($configuration[self::FACTORY_NAMESPACES]); | ||
| $this->factoryNamespaces = $configuration[self::FACTORY_NAMESPACES]; | ||
| } | ||
|
|
||
| /** | ||
| * @return array<class-string<Node>> | ||
| */ | ||
| public function getNodeTypes(): array | ||
| { | ||
| return [Class_::class]; | ||
| } | ||
|
|
||
| /** | ||
| * @param Class_ $node | ||
| */ | ||
| public function refactor(Node $node): ?Node | ||
| { | ||
| if (! $this->isObjectType($node, new ObjectType('Illuminate\Database\Eloquent\Model'))) { | ||
| return null; | ||
| } | ||
|
|
||
| $hasChanged = false; | ||
|
|
||
| foreach ($node->stmts as $stmt) { | ||
| if (! $stmt instanceof TraitUse) { | ||
| continue; | ||
| } | ||
|
|
||
| if (! $this->hasHasFactoryTrait($stmt)) { | ||
| continue; | ||
| } | ||
|
|
||
| if ($this->addUsePhpDocTag($stmt, $node)) { | ||
| $hasChanged = true; | ||
| } | ||
| } | ||
|
|
||
| if ($hasChanged) { | ||
| return $node; | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| private function hasHasFactoryTrait(TraitUse $traitUse): bool | ||
| { | ||
| foreach ($traitUse->traits as $trait) { | ||
| $traitName = $this->getName($trait); | ||
| if ($traitName === self::HAS_FACTORY_TRAIT) { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private function addUsePhpDocTag(TraitUse $traitUse, Class_ $class): bool | ||
| { | ||
| $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($traitUse); | ||
|
|
||
| if ($phpDocInfo->hasByName(self::USE_TAG_NAME)) { | ||
| return false; | ||
| } | ||
|
|
||
| $factoryClassName = $this->resolveFactoryClassName($class); | ||
| if ($factoryClassName === null) { | ||
| return false; | ||
| } | ||
|
|
||
| $phpDocTagNode = new PhpDocTagNode( | ||
| self::USE_TAG_NAME, | ||
| new UsesTagValueNode( | ||
| new GenericTypeNode( | ||
| new FullyQualifiedIdentifierTypeNode(self::HAS_FACTORY_TRAIT), | ||
| [new FullyQualifiedIdentifierTypeNode($factoryClassName)] | ||
| ), | ||
| '' | ||
| ) | ||
| ); | ||
|
|
||
| $phpDocInfo->addPhpDocTagNode($phpDocTagNode); | ||
|
|
||
| $this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($traitUse); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private function resolveFactoryClassName(Class_ $class): ?string | ||
| { | ||
| $factoryFromProperty = $this->getFactoryFromProperty($class); | ||
| if ($factoryFromProperty !== null) { | ||
| return $factoryFromProperty; | ||
| } | ||
|
|
||
| $className = $this->getName($class); | ||
| if ($className === null) { | ||
| return null; | ||
| } | ||
|
|
||
| $modelName = $this->nodeNameResolver->getShortName($className); | ||
|
|
||
| $factoryName = $modelName . 'Factory'; | ||
|
|
||
| $currentNamespace = $class->namespacedName?->toString() ?? $className; | ||
|
|
||
| $factoryClassNames = $this->getPotentialFactoryClassNames($currentNamespace, $factoryName); | ||
|
|
||
| foreach ($factoryClassNames as $factoryClassName) { | ||
| if ($this->reflectionProvider->hasClass($factoryClassName)) { | ||
| return $factoryClassName; | ||
| } | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| private function getFactoryFromProperty(Class_ $class): ?string | ||
| { | ||
| foreach ($class->stmts as $stmt) { | ||
| if (! $stmt instanceof Property) { | ||
| continue; | ||
| } | ||
|
|
||
| if (! $this->isName($stmt, 'factory')) { | ||
| continue; | ||
| } | ||
|
|
||
| if ($stmt->props[0]->default === null) { | ||
| continue; | ||
| } | ||
|
|
||
| $defaultValue = $stmt->props[0]->default; | ||
|
|
||
| if ($defaultValue instanceof ClassConstFetch) { | ||
| $factoryClassName = $this->getName($defaultValue->class); | ||
| if ($factoryClassName !== null && $this->reflectionProvider->hasClass($factoryClassName)) { | ||
| return $factoryClassName; | ||
| } | ||
| } | ||
|
|
||
| if ($defaultValue instanceof String_) { | ||
| $factoryClassName = $defaultValue->value; | ||
| if ($this->reflectionProvider->hasClass($factoryClassName)) { | ||
| return $factoryClassName; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * @return string[] | ||
| */ | ||
| private function getPotentialFactoryClassNames(string $modelNamespace, string $factoryName): array | ||
| { | ||
| $factoryClassNames = []; | ||
|
|
||
| foreach ($this->factoryNamespaces as $factoryNamespace) { | ||
| // Remove leading backslash if present | ||
| $factoryNamespace = ltrim($factoryNamespace, '\\'); | ||
|
|
||
| if (str_contains($modelNamespace, '\\Models\\')) { | ||
| $modelsPosition = strpos($modelNamespace, '\\Models\\'); | ||
| if ($modelsPosition === false) { | ||
| continue; | ||
| } | ||
| $afterModels = substr($modelNamespace, $modelsPosition + 8); | ||
|
|
||
| if (str_contains($afterModels, '\\')) { | ||
| $namespaceParts = explode('\\', $afterModels); | ||
| array_pop($namespaceParts); | ||
| $deepNamespace = implode('\\', $namespaceParts); | ||
|
|
||
| $factoryClassNames[] = '\\' . $factoryNamespace . '\\' . $deepNamespace . '\\' . $factoryName; | ||
| } | ||
| } elseif (str_contains($modelNamespace, 'App\\')) { | ||
| $appPosition = strpos($modelNamespace, 'App\\'); | ||
| if ($appPosition === false) { | ||
| continue; | ||
| } | ||
| $afterApp = substr($modelNamespace, $appPosition + 4); | ||
|
|
||
| if (str_contains($afterApp, '\\')) { | ||
| $namespaceParts = explode('\\', $afterApp); | ||
| array_pop($namespaceParts); | ||
| $deepNamespace = implode('\\', $namespaceParts); | ||
|
|
||
| $factoryClassNames[] = '\\' . $factoryNamespace . '\\' . $deepNamespace . '\\' . $factoryName; | ||
| } | ||
| } | ||
|
|
||
| $factoryClassNames[] = '\\' . $factoryNamespace . '\\' . $factoryName; | ||
| } | ||
|
|
||
| return array_unique($factoryClassNames); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can simplify this a lot, and even remove the subsequent
getPotentialFactoryClassNames()method.I think it's enough to replace in the
$class->namespacedName->toString(), theApp\ModelsorApppart withDatabase\Factories.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I kind of see what you mean but feel like this code is still needed to handle some edge cases after quickly playing with it. Happy to give it another shot if it's a deal breaker?