vierge-noire / cakephp-fixture-factories

CakePHP Fixture Factories
https://vierge-noire.github.io/
MIT License
85 stars 20 forks source link

Calling `with()` inside `setDefaultTemplate()` occurs unexpected increase of the associated entities #216

Closed ckbx-cakebox closed 1 year ago

ckbx-cakebox commented 1 year ago

For example, we supposed to have three tables; Authors, Articles, Comments. Article has many Comments and Authors.

  1. First we call with() method on hasMany associations inside setDefaultTemplate().

    class ArticleFactory extends BaseFactory
    {
    protected function setDefaultTemplate(): void
    {
        $this->setDefaultData(...)->with('Comments', CommentFactory::make());
    }
    }
  2. To call with() method with entity occurs unexpected increase of its associations.

$article = ArticleFactory::make()->persist();
print count($article->comments);  // 1

$author = AuthorFactory::make()->with('Articles', $article)->persist();
print count($article->comments);  // 2

Otherwise, do I have a mistake about the usage of the with() method?

ckbx-cakebox commented 1 year ago

Essentially, the problem is that DataCompiler::compileEntity() (does explicitly) ignore $dataFromDefaultTemplate but doesn't ignore $dataFromDefaultAssociations, when EntityInterface is injected. Thus I supposed it is a bug. I guess that both should be ignored.

The smallest reproductive code is the following:

$article = ArticleFactory::make()->persist();
print count($article->comments);  // 1

ArticleFactory::make($article)->persist();
print count($article->comments);  // 2
pabloelcolombiano commented 1 year ago

Yes, this looks like a bug, nice catch!

If you can fix the pipe (psalm), I'll merge that. https://github.com/vierge-noire/cakephp-fixture-factories/actions/runs/5845958439/job/16108103706

ckbx-cakebox commented 1 year ago

Thank you, I have just fixed the psalm error!

pabloelcolombiano commented 1 year ago

Merged, thank you!