FactoryBuilder.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. namespace Illuminate\Database\Eloquent;
  3. use Faker\Generator as Faker;
  4. use InvalidArgumentException;
  5. use Illuminate\Support\Traits\Macroable;
  6. class FactoryBuilder
  7. {
  8. use Macroable;
  9. /**
  10. * The model definitions in the container.
  11. *
  12. * @var array
  13. */
  14. protected $definitions;
  15. /**
  16. * The model being built.
  17. *
  18. * @var string
  19. */
  20. protected $class;
  21. /**
  22. * The name of the model being built.
  23. *
  24. * @var string
  25. */
  26. protected $name = 'default';
  27. /**
  28. * The database connection on which the model instance should be persisted.
  29. *
  30. * @var string
  31. */
  32. protected $connection;
  33. /**
  34. * The model states.
  35. *
  36. * @var array
  37. */
  38. protected $states;
  39. /**
  40. * The model after making callbacks.
  41. *
  42. * @var array
  43. */
  44. protected $afterMaking = [];
  45. /**
  46. * The model after creating callbacks.
  47. *
  48. * @var array
  49. */
  50. protected $afterCreating = [];
  51. /**
  52. * The states to apply.
  53. *
  54. * @var array
  55. */
  56. protected $activeStates = [];
  57. /**
  58. * The Faker instance for the builder.
  59. *
  60. * @var \Faker\Generator
  61. */
  62. protected $faker;
  63. /**
  64. * The number of models to build.
  65. *
  66. * @var int|null
  67. */
  68. protected $amount = null;
  69. /**
  70. * Create an new builder instance.
  71. *
  72. * @param string $class
  73. * @param string $name
  74. * @param array $definitions
  75. * @param array $states
  76. * @param array $afterMaking
  77. * @param array $afterCreating
  78. * @param \Faker\Generator $faker
  79. * @return void
  80. */
  81. public function __construct($class, $name, array $definitions, array $states,
  82. array $afterMaking, array $afterCreating, Faker $faker)
  83. {
  84. $this->name = $name;
  85. $this->class = $class;
  86. $this->faker = $faker;
  87. $this->states = $states;
  88. $this->definitions = $definitions;
  89. $this->afterMaking = $afterMaking;
  90. $this->afterCreating = $afterCreating;
  91. }
  92. /**
  93. * Set the amount of models you wish to create / make.
  94. *
  95. * @param int $amount
  96. * @return $this
  97. */
  98. public function times($amount)
  99. {
  100. $this->amount = $amount;
  101. return $this;
  102. }
  103. /**
  104. * Set the states to be applied to the model.
  105. *
  106. * @param array|mixed $states
  107. * @return $this
  108. */
  109. public function states($states)
  110. {
  111. $this->activeStates = is_array($states) ? $states : func_get_args();
  112. return $this;
  113. }
  114. /**
  115. * Set the database connection on which the model instance should be persisted.
  116. *
  117. * @param string $name
  118. * @return $this
  119. */
  120. public function connection($name)
  121. {
  122. $this->connection = $name;
  123. return $this;
  124. }
  125. /**
  126. * Create a model and persist it in the database if requested.
  127. *
  128. * @param array $attributes
  129. * @return \Closure
  130. */
  131. public function lazy(array $attributes = [])
  132. {
  133. return function () use ($attributes) {
  134. return $this->create($attributes);
  135. };
  136. }
  137. /**
  138. * Create a collection of models and persist them to the database.
  139. *
  140. * @param array $attributes
  141. * @return mixed
  142. */
  143. public function create(array $attributes = [])
  144. {
  145. $results = $this->make($attributes);
  146. if ($results instanceof Model) {
  147. $this->store(collect([$results]));
  148. $this->callAfterCreating(collect([$results]));
  149. } else {
  150. $this->store($results);
  151. $this->callAfterCreating($results);
  152. }
  153. return $results;
  154. }
  155. /**
  156. * Set the connection name on the results and store them.
  157. *
  158. * @param \Illuminate\Support\Collection $results
  159. * @return void
  160. */
  161. protected function store($results)
  162. {
  163. $results->each(function ($model) {
  164. if (! isset($this->connection)) {
  165. $model->setConnection($model->newQueryWithoutScopes()->getConnection()->getName());
  166. }
  167. $model->save();
  168. });
  169. }
  170. /**
  171. * Create a collection of models.
  172. *
  173. * @param array $attributes
  174. * @return mixed
  175. */
  176. public function make(array $attributes = [])
  177. {
  178. if ($this->amount === null) {
  179. return tap($this->makeInstance($attributes), function ($instance) {
  180. $this->callAfterMaking(collect([$instance]));
  181. });
  182. }
  183. if ($this->amount < 1) {
  184. return (new $this->class)->newCollection();
  185. }
  186. $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
  187. return $this->makeInstance($attributes);
  188. }, range(1, $this->amount)));
  189. $this->callAfterMaking($instances);
  190. return $instances;
  191. }
  192. /**
  193. * Create an array of raw attribute arrays.
  194. *
  195. * @param array $attributes
  196. * @return mixed
  197. */
  198. public function raw(array $attributes = [])
  199. {
  200. if ($this->amount === null) {
  201. return $this->getRawAttributes($attributes);
  202. }
  203. if ($this->amount < 1) {
  204. return [];
  205. }
  206. return array_map(function () use ($attributes) {
  207. return $this->getRawAttributes($attributes);
  208. }, range(1, $this->amount));
  209. }
  210. /**
  211. * Get a raw attributes array for the model.
  212. *
  213. * @param array $attributes
  214. * @return mixed
  215. *
  216. * @throws \InvalidArgumentException
  217. */
  218. protected function getRawAttributes(array $attributes = [])
  219. {
  220. if (! isset($this->definitions[$this->class][$this->name])) {
  221. throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}].");
  222. }
  223. $definition = call_user_func(
  224. $this->definitions[$this->class][$this->name],
  225. $this->faker, $attributes
  226. );
  227. return $this->expandAttributes(
  228. array_merge($this->applyStates($definition, $attributes), $attributes)
  229. );
  230. }
  231. /**
  232. * Make an instance of the model with the given attributes.
  233. *
  234. * @param array $attributes
  235. * @return \Illuminate\Database\Eloquent\Model
  236. */
  237. protected function makeInstance(array $attributes = [])
  238. {
  239. return Model::unguarded(function () use ($attributes) {
  240. $instance = new $this->class(
  241. $this->getRawAttributes($attributes)
  242. );
  243. if (isset($this->connection)) {
  244. $instance->setConnection($this->connection);
  245. }
  246. return $instance;
  247. });
  248. }
  249. /**
  250. * Apply the active states to the model definition array.
  251. *
  252. * @param array $definition
  253. * @param array $attributes
  254. * @return array
  255. */
  256. protected function applyStates(array $definition, array $attributes = [])
  257. {
  258. foreach ($this->activeStates as $state) {
  259. if (! isset($this->states[$this->class][$state])) {
  260. if ($this->stateHasAfterCallback($state)) {
  261. continue;
  262. }
  263. throw new InvalidArgumentException("Unable to locate [{$state}] state for [{$this->class}].");
  264. }
  265. $definition = array_merge(
  266. $definition,
  267. $this->stateAttributes($state, $attributes)
  268. );
  269. }
  270. return $definition;
  271. }
  272. /**
  273. * Get the state attributes.
  274. *
  275. * @param string $state
  276. * @param array $attributes
  277. * @return array
  278. */
  279. protected function stateAttributes($state, array $attributes)
  280. {
  281. $stateAttributes = $this->states[$this->class][$state];
  282. if (! is_callable($stateAttributes)) {
  283. return $stateAttributes;
  284. }
  285. return call_user_func(
  286. $stateAttributes,
  287. $this->faker, $attributes
  288. );
  289. }
  290. /**
  291. * Expand all attributes to their underlying values.
  292. *
  293. * @param array $attributes
  294. * @return array
  295. */
  296. protected function expandAttributes(array $attributes)
  297. {
  298. foreach ($attributes as &$attribute) {
  299. if (is_callable($attribute) && ! is_string($attribute) && ! is_array($attribute)) {
  300. $attribute = $attribute($attributes);
  301. }
  302. if ($attribute instanceof static) {
  303. $attribute = $attribute->create()->getKey();
  304. }
  305. if ($attribute instanceof Model) {
  306. $attribute = $attribute->getKey();
  307. }
  308. }
  309. return $attributes;
  310. }
  311. /**
  312. * Run after making callbacks on a collection of models.
  313. *
  314. * @param \Illuminate\Support\Collection $models
  315. * @return void
  316. */
  317. public function callAfterMaking($models)
  318. {
  319. $this->callAfter($this->afterMaking, $models);
  320. }
  321. /**
  322. * Run after creating callbacks on a collection of models.
  323. *
  324. * @param \Illuminate\Support\Collection $models
  325. * @return void
  326. */
  327. public function callAfterCreating($models)
  328. {
  329. $this->callAfter($this->afterCreating, $models);
  330. }
  331. /**
  332. * Call after callbacks for each model and state.
  333. *
  334. * @param array $afterCallbacks
  335. * @param \Illuminate\Support\Collection $models
  336. * @return void
  337. */
  338. protected function callAfter(array $afterCallbacks, $models)
  339. {
  340. $states = array_merge([$this->name], $this->activeStates);
  341. $models->each(function ($model) use ($states, $afterCallbacks) {
  342. foreach ($states as $state) {
  343. $this->callAfterCallbacks($afterCallbacks, $model, $state);
  344. }
  345. });
  346. }
  347. /**
  348. * Call after callbacks for each model and state.
  349. *
  350. * @param array $afterCallbacks
  351. * @param \Illuminate\Database\Eloquent\Model $model
  352. * @param string $state
  353. * @return void
  354. */
  355. protected function callAfterCallbacks(array $afterCallbacks, $model, $state)
  356. {
  357. if (! isset($afterCallbacks[$this->class][$state])) {
  358. return;
  359. }
  360. foreach ($afterCallbacks[$this->class][$state] as $callback) {
  361. $callback($model, $this->faker);
  362. }
  363. }
  364. /**
  365. * Determine if the given state has an "after" callback.
  366. *
  367. * @param string $state
  368. * @return bool
  369. */
  370. protected function stateHasAfterCallback($state)
  371. {
  372. return isset($this->afterMaking[$this->class][$state]) ||
  373. isset($this->afterCreating[$this->class][$state]);
  374. }
  375. }