PHP code example of soyhuce / array-factory

1. Go to this page and download the library: Download soyhuce/array-factory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

soyhuce / array-factory example snippets


use Soyhuce\ArrayFactory;

$factory = new ArrayFactory(['foo' => 'bar']); // from an array
$factory = ArrayFactory::new(['foo' => 'bar']); // from static method new
$factory = ArrayFactory::new(fn () => ['foo' => 'bar']); // with a callable
$factory = ArrayFactory::new(fn () => ['foo' => faker()->word() ]); // using \Faker\Generator generation

$factory->createOne();
// ['foo' => 'bar']
$factory->createMany(['foo' => 'qux'], ['foo' => 'bar'])
// [['foo' => 'qux'], ['foo' => 'bar']]
$factory->count(2)->asCollection();
// Illuminate\Support\Collection([ ['foo' => 'bar'], ['foo' => 'bar'] ])

$factory = new ArrayFactory(
    definition: ['foo' => 'bar'],
    states: [
        'qux' => ['foo' => 'qux'],
    ]
);

$factory->createOne();
// ['foo' => 'bar']
$factory->state('qux')->createOne();
// ['foo' => 'qux']

$factory = new ArrayFactory(
    collection: FooCollection::class,
);

$foo = FooFactory::new()->asCollection();

$factory = new ArrayFactory(
    data: FooData::class,
);

$factory = FooFactory::new()->asData();

$datas = $factory->manyAsDataCollection(['id' => 2], ['id' => 3]);
// Collection([FooData(id: 2), FooData(id: 3)])

class FooFactory extends ArrayFactory
{    
    protected string $collection = FooCollection::class;
    
    protected string $data = FooData::class;
    
    public function definition(): array
    {
        return [
            'id' => 1,
            'activated' => true,
            'message' => faker()->sentence(),
            'value' => 0,
        ];
    }

    public function id(int $id): static
    {
        return $this->state(['id' => $id]);
    }

    public function activated(bool $activated = true): static
    {
        return $this->state(['activated' => $activated]);
    }
}

    $foo1 = FooFactory::new()->createOne(); 
    // ['id' => 1, 'activated' => true, 'value' => 0]
    $foo1 = FooFactory::new()->createOne(['value' => 1]]);
     // ['id' => 1, 'activated' => true, 'value' => 1]
    $foo2 = FooFactory::new()->id(2)->createOne();
     // ['id' => 2, 'activated' => true, 'value' => 0]
    $foo3 = FooFactory::new()->activated(false)->createOne();
     // ['id' => 1, 'activated' => false, 'value' => 0]