digital-creative/fakeable-data-transfer-object

1.0.2 2022-12-23 16:51 UTC

This package is auto-updated.

Last update: 2024-11-23 20:42:38 UTC


README

Latest Version on Packagist Total Downloads License

This package extends the https://github.com/spatie/data-transfer-object by only including a new static method ::fake(), therefore expects no difference from the original package.

Installation

You can install the package via composer:

composer require digital-creative/fakeable-data-transfer-object

Dependencies:

Usage

use DigitalCreative\FakeableDataTransferObject\DataTransferObject;

class SomeObject extends DataTransferObject
{
    public string $name;
    public int $age;
}

then

$dto1 = SomeObject::fake();
$dto2 = SomeObject::fake(age: 18);

echo $dto1->name; // random word
echo $dto1->age; // random int

echo $dto2->name; // random word
echo $dto2->age; // 18

Register Custom Types

You can register any custom type by adding the following on the boot method of your AppServiceProvider:

<?php

namespace App\Providers;

use BenSampo\Enum\Enum;
use DigitalCreative\FakeableDataTransferObject\FakerRegistrar;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        FakerRegistrar::register(Enum::class, function (string $class, mixed $value = null) {
            return blank($value) ? $class::getRandomInstance() : $class::fromValue($value);
        });
        
        FakerRegistrar::register(UploadedFile::class, function (string $class, mixed $value = null) {
            /** @var UploadedFile $class */
            return blank($value) ? $class::fake()->create('file.png') : $value;
        });

    }
}

and use like:

use DigitalCreative\FakeableDataTransferObject\DataTransferObject;

class SomeObject extends DataTransferObject
{
    public GenderEnum $gender;
    public UploadedFile $attachment;
}

License

The MIT License (MIT). Please see License File for more information.