Created
July 26, 2018 13:43
-
-
Save jmsfwk/578b7134277e02805d8fbe23193b7ab0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeClient | |
{ | |
public function something() | |
{ | |
// ... | |
$this->userFactory->state('invalid')->create(); | |
// ... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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