Anteris-Dev / data-transfer-object-factory

Making it easy to mock your Data Transfer Objects
MIT License
37 stars 3 forks source link

Should auto create child DTO objects as well #5

Closed morrislaptop closed 3 years ago

morrislaptop commented 3 years ago
class Address extends DataTransferObject
{
    public string $line1;
}

class CreateOrder extends DataTransferObject
{
    public Address $address;
}

DataTransferObjectFactory::make(CreateOrderDTO::class);

I'd expect the the factory to detect that $address is a DTO of type Address and auto make that as well? What do you think?

aidan-casey commented 3 years ago

Hey @morrislaptop! You are correct, the factory should be returning a DTO in that scenario. It would appear that was an oversight on my part.

In the the initial stages of this package we did not follow Spatie's approach to type casting and allowed collections to be generated based on the property type in addition to doc block support. It looks like when we removed that approach and aligned this package with how Spatie does things, we inadvertently removed support for generating DTOs based on their type as well.

I will add this to the to do list, but in the meantime you can get around this in one of two ways:

Doc block

class Address extends DataTransferObject
{
    public string $line1;
}

class CreateOrder extends DataTransferObject
{
    /** @var Address */
    public Address $address;
}

DataTransferObjectFactory::make(CreateOrder::class);

Custom Factory

class Factory extends DataTransferObjectFactory
{
    public static function makeAddress(): Address
    {
        return static::make( Address::class );
    }
}

Thanks for opening this issue!

aidan-casey commented 3 years ago

Fixed! Just remember to use the FQDN in your DTO. 👍

morrislaptop commented 3 years ago

Nice! I had another idea as well - mapping DTO property names to faker instances e.g.

class Employee extends DataTransferObject { public string $address; }

Then instead of just calling $faker->word, we would call $faker->address, what do you think?

Example: https://github.com/mpociot/laravel-test-factory-helper

aidan-casey commented 3 years ago

Love this idea! Let me create a separate issue for that so we can track it there. May be a good time to implement this as we consider some changes for PHP 8 as well.