Skip to content
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

feat: support newFactory method when resolving factory #1922

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\DynamicStaticMethodReturnTypeExtension;
Expand All @@ -22,14 +23,17 @@
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;

use function basename;
use function class_exists;
use function count;
use function ltrim;
use function str_replace;

final class ModelFactoryDynamicStaticMethodReturnTypeExtension implements DynamicStaticMethodReturnTypeExtension
{
public function __construct(
private ReflectionProvider $reflectionProvider,
) {
}

public function getClass(): string
{
return Model::class;
Expand Down Expand Up @@ -68,18 +72,59 @@ public function getTypeFromStaticMethodCall(
$isSingleModel = (new UnionType($numericTypes))->isSuperTypeOf($argType)->negate();
}

$factoryName = Factory::resolveFactoryName(ltrim($class->toCodeString(), '\\')); // @phpstan-ignore-line
$factoryClass = $this->getFactoryClass($class, $scope);

if (class_exists($factoryName)) {
return new ModelFactoryType($factoryName, null, null, $isSingleModel);
if ($factoryClass === null) {
return new ErrorType();
}

$modelName = basename(str_replace('\\', '/', $class->toCodeString()));
return new ModelFactoryType($factoryClass, null, null, $isSingleModel);
}

if (! class_exists('Database\\Factories\\' . $modelName . 'Factory')) {
return new ErrorType();
private function getFactoryClass(Name $model, Scope $scope): string|null
{
$factoryClass = $this->getFactoryClassFromNewFactoryMethod($model, $scope);

if ($factoryClass !== null) {
return $factoryClass;
}

$factoryClass = Factory::resolveFactoryName(ltrim($model->toCodeString(), '\\')); // @phpstan-ignore-line

if (class_exists($factoryClass)) {
return $factoryClass;
}

return null;
}

private function getFactoryClassFromNewFactoryMethod(Name $model, Scope $scope): string|null
{
$modelReflection = $this->reflectionProvider->getClass($model->toString());

if (! $modelReflection->hasMethod('newFactory')) {
return null;
}

$returnType = $modelReflection->getMethod('newFactory', $scope)
->getVariants()[0]
->getReturnType();

$factoryClasses = $returnType->getObjectClassNames();

if (count($factoryClasses) !== 1) {
return null;
}

$factoryReflection = $this->reflectionProvider->getClass($factoryClasses[0]);

if (
! $factoryReflection->isSubclassOf(Factory::class)
|| $factoryReflection->isAbstract()
) {
return null;
}

return new ModelFactoryType('Database\\Factories\\' . $modelName . 'Factory', null, null, $isSingleModel);
return $factoryReflection->getName();
}
}
8 changes: 4 additions & 4 deletions tests/Type/data/model-factories.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ function dummy(?int $foo): void {
assertType('Database\Factories\UserFactory', User::factory()->afterCreating(fn (User $user) => $user));
assertType('Database\Factories\Domain\Foo\UserFactory', \App\Domain\Foo\User::factory());

assertType('Database\Factories\PostFactory', Post::factory());
assertType('Database\Factories\PostFactory', Post::factory()->new());
assertType('Database\Factories\Post\PostFactory', Post::factory());
assertType('Database\Factories\Post\PostFactory', Post::factory()->new());
assertType('App\Post', Post::factory()->createOne());
assertType('App\Post', Post::factory()->createOneQuietly());
assertType('Illuminate\Database\Eloquent\Collection<int, App\Post>', Post::factory()->createMany([]));
assertType('App\Post', Post::factory()->makeOne());
assertType('Database\Factories\PostFactory', Post::factory()->afterMaking(fn (Post $post) => $post));
assertType('Database\Factories\PostFactory', Post::factory()->afterCreating(fn (Post $post) => $post));
assertType('Database\Factories\Post\PostFactory', Post::factory()->afterMaking(fn (Post $post) => $post));
assertType('Database\Factories\Post\PostFactory', Post::factory()->afterCreating(fn (Post $post) => $post));

assertType('App\User|Illuminate\Database\Eloquent\Collection<int, App\User>', User::factory()->count($foo)->create());
assertType('App\User|Illuminate\Database\Eloquent\Collection<int, App\User>', User::factory()->count($foo)->createQuietly());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ class ModelFactoryDynamicStaticMethodReturnTypeExtensionTest extends PHPStanTest
public function it_sets_the_is_single_model_flag_to_true_if_no_args_given(): void
{
$scope = $this->createMock(Scope::class);
$extension = new ModelFactoryDynamicStaticMethodReturnTypeExtension();
$extension = new ModelFactoryDynamicStaticMethodReturnTypeExtension(
$this->createReflectionProvider(),
);

$type = $extension->getTypeFromStaticMethodCall(
new DummyMethodReflection('factory'), // @phpstan-ignore-line
Expand All @@ -54,7 +56,9 @@ public function it_sets_the_is_single_model_flag_to_true_if_no_args_given(): voi
public function it_sets_the_is_single_model_flag_correctly(Type $phpstanType, TrinaryLogic $expected): void
{
$scope = $this->createMock(Scope::class);
$extension = new ModelFactoryDynamicStaticMethodReturnTypeExtension();
$extension = new ModelFactoryDynamicStaticMethodReturnTypeExtension(
$this->createReflectionProvider(),
);

$scope->method('getType')->willReturn($phpstanType);

Expand Down
8 changes: 8 additions & 0 deletions tests/application/app/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace App;

use Database\Factories\Post\PostFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

Expand Down Expand Up @@ -31,4 +33,10 @@ public function newEloquentBuilder($query): PostBuilder
{
return new PostBuilder($query);
}

/** @return PostFactory */
protected static function newFactory(): Factory
{
return PostFactory::new();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

declare(strict_types=1);

namespace Database\Factories;
namespace Database\Factories\Post;

use App\Post;
use App\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* This is specifically testing a factory
* that is not in the expected namespace.
*
* @extends Factory<Post>
*/
class PostFactory extends Factory
Expand Down