<?php
namespace think\migration;
use ArrayAccess;
use Faker\Generator as Faker;
class Factory implements ArrayAccess
{
protected $definitions = [];
protected $states = [];
protected $afterMaking = [];
protected $afterCreating = [];
protected $faker;
public function __construct(Faker $faker)
{
$this->faker = $faker;
}
public function defineAs(string $class, string $name, callable $attributes)
{
return $this->define($class, $attributes, $name);
}
public function define(string $class, callable $attributes, string $name = 'default')
{
$this->definitions[$class][$name] = $attributes;
return $this;
}
public function state(string $class, string $state, $attributes)
{
$this->states[$class][$state] = $attributes;
return $this;
}
public function afterMaking(string $class, callable $callback, string $name = 'default')
{
$this->afterMaking[$class][$name][] = $callback;
return $this;
}
public function afterMakingState(string $class, string $state, callable $callback)
{
return $this->afterMaking($class, $callback, $state);
}
public function afterCreating(string $class, callable $callback, string $name = 'default')
{
$this->afterCreating[$class][$name][] = $callback;
return $this;
}
public function afterCreatingState(string $class, string $state, callable $callback)
{
return $this->afterCreating($class, $callback, $state);
}
public function create(string $class, array $attributes = [])
{
return $this->of($class)->create($attributes);
}
public function createAs(string $class, string $name, array $attributes = [])
{
return $this->of($class, $name)->create($attributes);
}
public function make(string $class, array $attributes = [])
{
return $this->of($class)->make($attributes);
}
public function makeAs(string $class, string $name, array $attributes = [])
{
return $this->of($class, $name)->make($attributes);
}
public function rawOf(string $class, string $name, array $attributes = [])
{
return $this->raw($class, $attributes, $name);
}
public function raw(string $class, array $attributes = [], string $name = 'default')
{
return array_merge(
call_user_func($this->definitions[$class][$name], $this->faker), $attributes
);
}
public function of(string $class, string $name = 'default')
{
return new FactoryBuilder(
$class, $name, $this->definitions, $this->states,
$this->afterMaking, $this->afterCreating, $this->faker
);
}
public function load(string $path)
{
$factory = $this;
if (is_dir($path)) {
foreach (glob($path . '*.php') as $file) {
require $file;
}
}
return $factory;
}
public function offsetExists($offset)
{
return isset($this->definitions[$offset]);
}
public function offsetGet($offset)
{
return $this->make($offset);
}
public function offsetSet($offset, $value)
{
$this->define($offset, $value);
}
public function offsetUnset($offset)
{
unset($this->definitions[$offset]);
}
}