Skip to content

Instantly share code, notes, and snippets.

@jmsfwk
Created July 26, 2018 13:43
Show Gist options
  • Save jmsfwk/578b7134277e02805d8fbe23193b7ab0 to your computer and use it in GitHub Desktop.
Save jmsfwk/578b7134277e02805d8fbe23193b7ab0 to your computer and use it in GitHub Desktop.
<?php
abstract class Factory
{
/** @var \Illuminate\Database\ConnectionInterface */
private $database;
/** @var \Faker\Generator */
protected $faker;
protected $attributes = [];
protected $states = [];
/**
* Factory constructor.
*
* @param \Illuminate\Database\ConnectionInterface $database
* @param \Faker\Generator $faker
*/
public function __construct(\Illuminate\Database\ConnectionInterface $database, \Faker\Generator $faker)
{
$this->database = $database;
$this->faker = $faker;
$this->attributes = $this->base($this->faker);
$this->states = $this->states($this->faker);
}
abstract protected function table(): string;
/**
* Define the base for the model here
* @return array
*/
protected function base(): array
{
return [];
}
/**
* Define states for the model here
* @return array
*/
protected function states(): array
{
return [];
}
protected function build()
{
$this->database->table($this->table())
->insert($this->attributes);
}
protected function create(array $attributes = [])
{
$this->mergeAttributes($attributes);
return $this->build();
}
protected function mergeAttributes(array $attributes): void
{
$this->attributes = array_merge($this->attributes, $attributes);
}
}
<?php
class SomeClient
{
public function something()
{
// ...
$this->userFactory->state('invalid')->create();
// ...
}
}
<?php
class UserFactory extends Factory
{
protected function base(\Faker\Generator $faker): array
{
return [
'email' => $faker->email,
];
}
protected function states(): array
{
return [
'invalid' => [
'latest_status' => 'invalid',
],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment