Login to bookmark this video
Buy Access to Course
23.

QuestionTag Fixtures & DateTimeImmutable with Faker

Share this awesome video!

|

Keep on Learning!

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

We no longer have a ManyToMany relationship between Question and Tag. Instead, each Question has many QuestionTag objects and each QuestionTag object is related to one Tag. This means that setting and using this relation - the relationship between Question and Tag - just changed. Let's update the fixtures to reflect this.

Generating & Configuring the QuestionTag Factory

First, since we now have a QuestionTag entity, we are going to be creating and persisting QuestionTag objects directly. So let's generate a Foundry factory for it. At your terminal, run:

symfony console make:factory

And choose QuestionTag. Go open that up: src/Factory/QuestionTagFactory.php.

59 lines | src/Factory/QuestionTagFactory.php
// ... lines 1 - 2
namespace App\Factory;
use App\Entity\QuestionTag;
use App\Repository\QuestionTagRepository;
use Zenstruck\Foundry\RepositoryProxy;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
// ... lines 11 - 28
final class QuestionTagFactory extends ModelFactory
{
public function __construct()
{
parent::__construct();
// TODO inject services if required (https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services)
}
protected function getDefaults(): array
{
return [
// TODO add your default values here (https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories)
'taggedAt' => self::faker()->datetime(),
];
}
protected function initialize(): self
{
// see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
return $this
// ->afterInstantiate(function(QuestionTag $questionTag) {})
;
}
protected static function getClass(): string
{
return QuestionTag::class;
}
}

In getDefaults(), our job, as usual, is to add all the required fields. Set question to QuestionFactory::new() and do the same thing for tag, setting that to TagFactory::new().

60 lines | src/Factory/QuestionTagFactory.php
// ... lines 1 - 28
final class QuestionTagFactory extends ModelFactory
{
// ... lines 31 - 37
protected function getDefaults(): array
{
return [
'question' => QuestionFactory::new(),
'tag' => TagFactory::new(),
'taggedAt' => self::faker()->datetime(),
];
}
// ... lines 46 - 58
}

As a reminder, the new() method returns a QuestionFactory instance. So we're assigning the question attribute to a QuestionFactory object. We talked earlier about how this is better than calling createOne() because, when you set a relationship property to a factory instance, Foundry will use that to create the Question object... but only if it needs to.

Anyways with this setup, when we use this factory, it will create a brand new Question and a brand new Tag each time it makes a QuestionTag.

We can see this. Open up the fixtures class and say QuestionTagFactory::createMany(10). I'm going to put a return statement here because some of the code below is currently broken.

51 lines | src/DataFixtures/AppFixtures.php
// ... lines 1 - 9
use App\Factory\QuestionTagFactory;
// ... lines 11 - 14
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
TagFactory::createMany(100);
QuestionTagFactory::createMany(10);
return;
// ... lines 24 - 48
}
}

Let's try this:

symfony console doctrine:fixtures:load

Handling DateTimeImmutable & Faker

And... it fails! But... for an unrelated reason. It says:

QuestionTag::setTaggedAt() argument 1 must be a DateTimeImmutable instance, DateTime given.

This is subtle... and related to Faker. In Faker, when you say self::faker()->datetime(), that returns a DateTime object. No surprise!

But if you look at the QuestionTag entity, the taggedAt field is set to a datetime_immutable Doctrine type. This means that, instead of that property being a DateTime object, it will be a DateTimeImmutable object. Really... the same thing... except that DateTimeImmutable objects can't be changed.

The point is, the type-hint on the setter is DateTimeImmutable... but we're trying to pass a DateTime instance... which isn't the same. The easiest way to fix this is to update the fixtures. Wrap the value with DateTimeImmutable::createFromMutable()... which is a method that exists just for this situation.

60 lines | src/Factory/QuestionTagFactory.php
// ... lines 1 - 28
final class QuestionTagFactory extends ModelFactory
{
// ... lines 31 - 37
protected function getDefaults(): array
{
return [
// ... lines 41 - 42
'taggedAt' => \DateTimeImmutable::createFromMutable(self::faker()->datetime()),
];
}
// ... lines 46 - 58
}

And if we reload the fixtures now...

symfony console doctrine:fixtures:load

No errors! Run:

symfony console doctrine:query:sql 'SELECT * FROM question_tag'

And... cool! We have 10 rows. Now query the question table:

symfony console doctrine:query:sql 'SELECT * FROM question'

And this also has 10 rows. That proves that, each time the factory creates a QuestionTag, it creates a brand new Question to relate to it.

So... this works... but it's not really what we want. Instead of creating new questions, we want to relate each QuestionTag to one of the published questions that we're creating in our fixtures.

Let's do that next, by doing some seriously cool stuff with Foundry.