zenstruck / foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html
MIT License
643 stars 70 forks source link

Proxy objetc TypeError #545

Closed gseganzerla closed 9 months ago

gseganzerla commented 9 months ago

I´m getting a error with type-hint and with the Proxy object returned by my Factory.

I have the following code on my service layer

public function add(Table $table): void
    {
        $this->repository->add($table);
        $this->entityManager->flush();
    }

and the following test

public function testTableWasAdded(): void
    {
        $this->tableRepository->expects($this->once())
            ->method('add');

        $this->entityManager->expects($this->once())
            ->method('flush');

        $this->service->add(TableFactory::createOne()); // the error is here
    }

The error that I got on the marked line is TypeError: App\Service\TableService::add(): Argument #1 ($table) must be of type App\Entity\Table, Zenstruck\Foundry\Proxy given, called in /var/www/tests/Unit/Service/TableServiceTest.php on line 77

I didn't undestand why Im getting this error because the docs says that the Proxy object that will be returned will be automatically type-hinted to a Table object (In this case, the table object is my entity).

The code works ok when I call the object method in the Proxy object returned because its a Table itself.

nikophil commented 9 months ago

Hi,

the way to go here is indeed to call the ->object() method. Foundry's proxy are so-called proxy, but they are actually a wrapper around your entities.

I didn't undestand why Im getting this error because the docs says that the Proxy object that will be returned will be automatically type-hinted to a Table object

I think you refer to this sentence in the docs

the "Proxy" magically calls the underlying Post methods and is type-hinted to "Post"

This statement i falsy, and I think it refers to the IDE which sees the proxy as post

gseganzerla commented 9 months ago

This statement i falsy, and I think it refers to the IDE which sees the proxy as post

Hi @nikophil

I think I understood now. That sentence in the docs refrers just to the IDE capabilities and not to type-hinted params. So, I really need to call the ->object() method to fix the type hint problem.

Thanks for your time and help.