FactoryBuilder.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace think\migration;
  3. use Faker\Generator as Faker;
  4. use InvalidArgumentException;
  5. use think\Collection;
  6. use think\Model;
  7. class FactoryBuilder
  8. {
  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
  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 $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(new Collection([$results]));
  158. $this->callAfterCreating(new Collection([$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 Collection $results
  169. * @return void
  170. */
  171. protected function store($results)
  172. {
  173. $results->each(function (Model $model) {
  174. $model->save();
  175. });
  176. }
  177. /**
  178. * Create a collection of models.
  179. *
  180. * @param array $attributes
  181. * @return mixed
  182. */
  183. public function make(array $attributes = [])
  184. {
  185. if ($this->amount === null) {
  186. return tap($this->makeInstance($attributes), function ($instance) {
  187. $this->callAfterMaking(new Collection([$instance]));
  188. });
  189. }
  190. if ($this->amount < 1) {
  191. return (new $this->class)->toCollection();
  192. }
  193. $instances = (new $this->class)->toCollection(array_map(function () use ($attributes) {
  194. return $this->makeInstance($attributes);
  195. }, range(1, $this->amount)));
  196. $this->callAfterMaking($instances);
  197. return $instances;
  198. }
  199. /**
  200. * Create an array of raw attribute arrays.
  201. *
  202. * @param array $attributes
  203. * @return mixed
  204. */
  205. public function raw(array $attributes = [])
  206. {
  207. if ($this->amount === null) {
  208. return $this->getRawAttributes($attributes);
  209. }
  210. if ($this->amount < 1) {
  211. return [];
  212. }
  213. return array_map(function () use ($attributes) {
  214. return $this->getRawAttributes($attributes);
  215. }, range(1, $this->amount));
  216. }
  217. /**
  218. * Get a raw attributes array for the model.
  219. *
  220. * @param array $attributes
  221. * @return mixed
  222. *
  223. * @throws \InvalidArgumentException
  224. */
  225. protected function getRawAttributes(array $attributes = [])
  226. {
  227. if (!isset($this->definitions[$this->class][$this->name])) {
  228. throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}].");
  229. }
  230. $definition = call_user_func(
  231. $this->definitions[$this->class][$this->name],
  232. $this->faker, $attributes
  233. );
  234. return $this->expandAttributes(
  235. array_merge($this->applyStates($definition, $attributes), $attributes)
  236. );
  237. }
  238. /**
  239. * Make an instance of the model with the given attributes.
  240. *
  241. * @param array $attributes
  242. * @return Model
  243. */
  244. protected function makeInstance(array $attributes = [])
  245. {
  246. return new $this->class(
  247. $this->getRawAttributes($attributes)
  248. );
  249. }
  250. /**
  251. * Apply the active states to the model definition array.
  252. *
  253. * @param array $definition
  254. * @param array $attributes
  255. * @return array
  256. */
  257. protected function applyStates(array $definition, array $attributes = [])
  258. {
  259. foreach ($this->activeStates as $state) {
  260. if (!isset($this->states[$this->class][$state])) {
  261. if ($this->stateHasAfterCallback($state)) {
  262. continue;
  263. }
  264. throw new InvalidArgumentException("Unable to locate [{$state}] state for [{$this->class}].");
  265. }
  266. $definition = array_merge(
  267. $definition,
  268. $this->stateAttributes($state, $attributes)
  269. );
  270. }
  271. return $definition;
  272. }
  273. /**
  274. * Get the state attributes.
  275. *
  276. * @param string $state
  277. * @param array $attributes
  278. * @return array
  279. */
  280. protected function stateAttributes($state, array $attributes)
  281. {
  282. $stateAttributes = $this->states[$this->class][$state];
  283. if (!is_callable($stateAttributes)) {
  284. return $stateAttributes;
  285. }
  286. return call_user_func(
  287. $stateAttributes,
  288. $this->faker, $attributes
  289. );
  290. }
  291. /**
  292. * Expand all attributes to their underlying values.
  293. *
  294. * @param array $attributes
  295. * @return array
  296. */
  297. protected function expandAttributes(array $attributes)
  298. {
  299. foreach ($attributes as &$attribute) {
  300. if (is_callable($attribute) && !is_string($attribute) && !is_array($attribute)) {
  301. $attribute = $attribute($attributes);
  302. }
  303. if ($attribute instanceof static) {
  304. $attribute = $attribute->create()->getKey();
  305. }
  306. if ($attribute instanceof Model) {
  307. $attribute = $attribute->getKey();
  308. }
  309. }
  310. return $attributes;
  311. }
  312. /**
  313. * Run after making callbacks on a collection of models.
  314. *
  315. * @param Collection $models
  316. * @return void
  317. */
  318. public function callAfterMaking($models)
  319. {
  320. $this->callAfter($this->afterMaking, $models);
  321. }
  322. /**
  323. * Run after creating callbacks on a collection of models.
  324. *
  325. * @param Collection $models
  326. * @return void
  327. */
  328. public function callAfterCreating($models)
  329. {
  330. $this->callAfter($this->afterCreating, $models);
  331. }
  332. /**
  333. * Call after callbacks for each model and state.
  334. *
  335. * @param array $afterCallbacks
  336. * @param Collection $models
  337. * @return void
  338. */
  339. protected function callAfter(array $afterCallbacks, $models)
  340. {
  341. $states = array_merge([$this->name], $this->activeStates);
  342. $models->each(function ($model) use ($states, $afterCallbacks) {
  343. foreach ($states as $state) {
  344. $this->callAfterCallbacks($afterCallbacks, $model, $state);
  345. }
  346. });
  347. }
  348. /**
  349. * Call after callbacks for each model and state.
  350. *
  351. * @param array $afterCallbacks
  352. * @param Model $model
  353. * @param string $state
  354. * @return void
  355. */
  356. protected function callAfterCallbacks(array $afterCallbacks, $model, $state)
  357. {
  358. if (!isset($afterCallbacks[$this->class][$state])) {
  359. return;
  360. }
  361. foreach ($afterCallbacks[$this->class][$state] as $callback) {
  362. $callback($model, $this->faker);
  363. }
  364. }
  365. /**
  366. * Determine if the given state has an "after" callback.
  367. *
  368. * @param string $state
  369. * @return bool
  370. */
  371. protected function stateHasAfterCallback($state)
  372. {
  373. return isset($this->afterMaking[$this->class][$state]) ||
  374. isset($this->afterCreating[$this->class][$state]);
  375. }
  376. }