FactoryBuilder.php 11 KB

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