FactoryBuilder.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 state to be applied to the model.
  105. *
  106. * @param string $state
  107. * @return $this
  108. */
  109. public function state($state)
  110. {
  111. return $this->states([$state]);
  112. }
  113. /**
  114. * Set the states to be applied to the model.
  115. *
  116. * @param array|mixed $states
  117. * @return $this
  118. */
  119. public function states($states)
  120. {
  121. $this->activeStates = is_array($states) ? $states : func_get_args();
  122. return $this;
  123. }
  124. /**
  125. * Set the database connection on which the model instance should be persisted.
  126. *
  127. * @param string $name
  128. * @return $this
  129. */
  130. public function connection($name)
  131. {
  132. $this->connection = $name;
  133. return $this;
  134. }
  135. /**
  136. * Create a model and persist it in the database if requested.
  137. *
  138. * @param array $attributes
  139. * @return \Closure
  140. */
  141. public function lazy(array $attributes = [])
  142. {
  143. return function () use ($attributes) {
  144. return $this->create($attributes);
  145. };
  146. }
  147. /**
  148. * Create a collection of models and persist them to the database.
  149. *
  150. * @param array $attributes
  151. * @return mixed
  152. */
  153. public function create(array $attributes = [])
  154. {
  155. $results = $this->make($attributes);
  156. if ($results instanceof Model) {
  157. $this->store(collect([$results]));
  158. $this->callAfterCreating(collect([$results]));
  159. } else {
  160. $this->store($results);
  161. $this->callAfterCreating($results);
  162. }
  163. return $results;
  164. }
  165. /**
  166. * Set the connection name on the results and store them.
  167. *
  168. * @param \Illuminate\Support\Collection $results
  169. * @return void
  170. */
  171. protected function store($results)
  172. {
  173. $results->each(function ($model) {
  174. if (! isset($this->connection)) {
  175. $model->setConnection($model->newQueryWithoutScopes()->getConnection()->getName());
  176. }
  177. $model->save();
  178. });
  179. }
  180. /**
  181. * Create a collection of models.
  182. *
  183. * @param array $attributes
  184. * @return mixed
  185. */
  186. public function make(array $attributes = [])
  187. {
  188. if ($this->amount === null) {
  189. return tap($this->makeInstance($attributes), function ($instance) {
  190. $this->callAfterMaking(collect([$instance]));
  191. });
  192. }
  193. if ($this->amount < 1) {
  194. return (new $this->class)->newCollection();
  195. }
  196. $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
  197. return $this->makeInstance($attributes);
  198. }, range(1, $this->amount)));
  199. $this->callAfterMaking($instances);
  200. return $instances;
  201. }
  202. /**
  203. * Create an array of raw attribute arrays.
  204. *
  205. * @param array $attributes
  206. * @return mixed
  207. */
  208. public function raw(array $attributes = [])
  209. {
  210. if ($this->amount === null) {
  211. return $this->getRawAttributes($attributes);
  212. }
  213. if ($this->amount < 1) {
  214. return [];
  215. }
  216. return array_map(function () use ($attributes) {
  217. return $this->getRawAttributes($attributes);
  218. }, range(1, $this->amount));
  219. }
  220. /**
  221. * Get a raw attributes array for the model.
  222. *
  223. * @param array $attributes
  224. * @return mixed
  225. *
  226. * @throws \InvalidArgumentException
  227. */
  228. protected function getRawAttributes(array $attributes = [])
  229. {
  230. if (! isset($this->definitions[$this->class][$this->name])) {
  231. throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}].");
  232. }
  233. $definition = call_user_func(
  234. $this->definitions[$this->class][$this->name],
  235. $this->faker, $attributes
  236. );
  237. return $this->expandAttributes(
  238. array_merge($this->applyStates($definition, $attributes), $attributes)
  239. );
  240. }
  241. /**
  242. * Make an instance of the model with the given attributes.
  243. *
  244. * @param array $attributes
  245. * @return \Illuminate\Database\Eloquent\Model
  246. */
  247. protected function makeInstance(array $attributes = [])
  248. {
  249. return Model::unguarded(function () use ($attributes) {
  250. $instance = new $this->class(
  251. $this->getRawAttributes($attributes)
  252. );
  253. if (isset($this->connection)) {
  254. $instance->setConnection($this->connection);
  255. }
  256. return $instance;
  257. });
  258. }
  259. /**
  260. * Apply the active states to the model definition array.
  261. *
  262. * @param array $definition
  263. * @param array $attributes
  264. * @return array
  265. *
  266. * @throws \InvalidArgumentException
  267. */
  268. protected function applyStates(array $definition, array $attributes = [])
  269. {
  270. foreach ($this->activeStates as $state) {
  271. if (! isset($this->states[$this->class][$state])) {
  272. if ($this->stateHasAfterCallback($state)) {
  273. continue;
  274. }
  275. throw new InvalidArgumentException("Unable to locate [{$state}] state for [{$this->class}].");
  276. }
  277. $definition = array_merge(
  278. $definition,
  279. $this->stateAttributes($state, $attributes)
  280. );
  281. }
  282. return $definition;
  283. }
  284. /**
  285. * Get the state attributes.
  286. *
  287. * @param string $state
  288. * @param array $attributes
  289. * @return array
  290. */
  291. protected function stateAttributes($state, array $attributes)
  292. {
  293. $stateAttributes = $this->states[$this->class][$state];
  294. if (! is_callable($stateAttributes)) {
  295. return $stateAttributes;
  296. }
  297. return call_user_func(
  298. $stateAttributes,
  299. $this->faker, $attributes
  300. );
  301. }
  302. /**
  303. * Expand all attributes to their underlying values.
  304. *
  305. * @param array $attributes
  306. * @return array
  307. */
  308. protected function expandAttributes(array $attributes)
  309. {
  310. foreach ($attributes as &$attribute) {
  311. if (is_callable($attribute) && ! is_string($attribute) && ! is_array($attribute)) {
  312. $attribute = $attribute($attributes);
  313. }
  314. if ($attribute instanceof static) {
  315. $attribute = $attribute->create()->getKey();
  316. }
  317. if ($attribute instanceof Model) {
  318. $attribute = $attribute->getKey();
  319. }
  320. }
  321. return $attributes;
  322. }
  323. /**
  324. * Run after making callbacks on a collection of models.
  325. *
  326. * @param \Illuminate\Support\Collection $models
  327. * @return void
  328. */
  329. public function callAfterMaking($models)
  330. {
  331. $this->callAfter($this->afterMaking, $models);
  332. }
  333. /**
  334. * Run after creating callbacks on a collection of models.
  335. *
  336. * @param \Illuminate\Support\Collection $models
  337. * @return void
  338. */
  339. public function callAfterCreating($models)
  340. {
  341. $this->callAfter($this->afterCreating, $models);
  342. }
  343. /**
  344. * Call after callbacks for each model and state.
  345. *
  346. * @param array $afterCallbacks
  347. * @param \Illuminate\Support\Collection $models
  348. * @return void
  349. */
  350. protected function callAfter(array $afterCallbacks, $models)
  351. {
  352. $states = array_merge([$this->name], $this->activeStates);
  353. $models->each(function ($model) use ($states, $afterCallbacks) {
  354. foreach ($states as $state) {
  355. $this->callAfterCallbacks($afterCallbacks, $model, $state);
  356. }
  357. });
  358. }
  359. /**
  360. * Call after callbacks for each model and state.
  361. *
  362. * @param array $afterCallbacks
  363. * @param \Illuminate\Database\Eloquent\Model $model
  364. * @param string $state
  365. * @return void
  366. */
  367. protected function callAfterCallbacks(array $afterCallbacks, $model, $state)
  368. {
  369. if (! isset($afterCallbacks[$this->class][$state])) {
  370. return;
  371. }
  372. foreach ($afterCallbacks[$this->class][$state] as $callback) {
  373. $callback($model, $this->faker);
  374. }
  375. }
  376. /**
  377. * Determine if the given state has an "after" callback.
  378. *
  379. * @param string $state
  380. * @return bool
  381. */
  382. protected function stateHasAfterCallback($state)
  383. {
  384. return isset($this->afterMaking[$this->class][$state]) ||
  385. isset($this->afterCreating[$this->class][$state]);
  386. }
  387. }