EloquentRepository.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. namespace Dcat\Admin\Repositories;
  3. use Dcat\Admin\Form;
  4. use Dcat\Admin\Grid;
  5. use Dcat\Admin\Show;
  6. use Illuminate\Database\Eloquent\Model as EloquentModel;
  7. use Illuminate\Database\Eloquent\SoftDeletes;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Database\Eloquent\Relations;
  12. use Illuminate\Support\Str;
  13. use Spatie\EloquentSortable\Sortable;
  14. abstract class EloquentRepository extends Repository
  15. {
  16. /**
  17. * @var string
  18. */
  19. protected $eloquentClass;
  20. /**
  21. * @var EloquentModel
  22. */
  23. protected $model;
  24. public function __construct()
  25. {
  26. $this->setKeyName($this->eloquent()->getKeyName());
  27. $this->setIsSoftDeletes(
  28. in_array(SoftDeletes::class, class_uses($this->eloquent()))
  29. );
  30. }
  31. /**
  32. * @return string
  33. */
  34. public function getCreatedAtColumn()
  35. {
  36. return $this->eloquent()->getCreatedAtColumn();
  37. }
  38. /**
  39. * @return string
  40. */
  41. public function getUpdatedAtColumn()
  42. {
  43. return $this->eloquent()->getUpdatedAtColumn();
  44. }
  45. /**
  46. * Get columns of the grid.
  47. *
  48. * @return array
  49. */
  50. public function getGridColumns()
  51. {
  52. return ['*'];
  53. }
  54. /**
  55. * Get columns of the form.
  56. *
  57. * @return array
  58. */
  59. public function getFormColumns()
  60. {
  61. return ['*'];
  62. }
  63. /**
  64. * Get columns of the detail view.
  65. *
  66. * @return array
  67. */
  68. public function getDetailColumns()
  69. {
  70. return ['*'];
  71. }
  72. /**
  73. * Get the grid data.
  74. *
  75. * @param Grid\Model $model
  76. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Collection|array
  77. */
  78. public function get(Grid\Model $model)
  79. {
  80. $eloquent = $this->eloquent();
  81. $model->getQueries()->unique()->each(function ($query) use (&$eloquent) {
  82. if ($query['method'] == 'paginate') {
  83. $query['arguments'][1] = $this->getGridColumns();
  84. } elseif ($query['method'] == 'get') {
  85. $query['arguments'] = $this->getGridColumns();
  86. }
  87. $eloquent = call_user_func_array([$eloquent, $query['method']], $query['arguments'] ?? []);
  88. });
  89. return $eloquent;
  90. }
  91. /**
  92. * Get data to build edit form.
  93. *
  94. * @param Form $form
  95. * @return array
  96. */
  97. public function edit(Form $form): array
  98. {
  99. $eloquent = $this->eloquent();
  100. if ($this->isSoftDeletes) {
  101. $eloquent = $eloquent->withTrashed();
  102. }
  103. $this->model = $eloquent
  104. ->with($this->getRelations($form))
  105. ->findOrFail($form->getKey(), $this->getFormColumns());
  106. return $this->model->toArray();
  107. }
  108. /**
  109. * Get detail data.
  110. *
  111. * @param Show $show
  112. * @return array
  113. */
  114. public function detail(Show $show): array
  115. {
  116. $eloquent = $this->eloquent();
  117. if ($this->isSoftDeletes) {
  118. $eloquent = $eloquent->withTrashed();
  119. }
  120. $this->model = $eloquent
  121. ->with($this->getRelations($show))
  122. ->findOrFail($show->getId(), $this->getDetailColumns());
  123. return $this->model->toArray();
  124. }
  125. /**
  126. * Store a new record.
  127. *
  128. * @param Form $form
  129. * @return mixed
  130. */
  131. public function store(Form $form)
  132. {
  133. $result = null;
  134. DB::transaction(function () use ($form, &$result) {
  135. $model = $this->eloquent();
  136. $updates = $form->getUpdates();
  137. $relations = $this->getRelationInputs($model, $updates);
  138. if ($relations) {
  139. $updates = Arr::except($updates, array_keys($relations));
  140. }
  141. foreach ($updates as $column => $value) {
  142. $model->setAttribute($column, $value);
  143. }
  144. $result = $model->save();
  145. $this->updateRelation($form, $model, $relations);
  146. });
  147. return $this->eloquent()->getKey();
  148. }
  149. /**
  150. * Get data before update.
  151. *
  152. * @param Form $form
  153. * @return array
  154. */
  155. public function getDataWhenUpdating(Form $form): array
  156. {
  157. return $this->edit($form);
  158. }
  159. /**
  160. * Update form data.
  161. *
  162. * @param Form $form
  163. * @return bool
  164. */
  165. public function update(Form $form)
  166. {
  167. /* @var EloquentModel $builder */
  168. $model = $this->eloquent();
  169. if (!$model->getKey()) {
  170. $model->exists = true;
  171. $model->setAttribute($model->getKeyName(), $form->getKey());
  172. }
  173. $result = null;
  174. DB::transaction(function () use ($form, $model, &$result) {
  175. $updates = $form->getUpdates();
  176. $relations = $this->getRelationInputs($model, $updates);
  177. $updates = Arr::except($updates, array_keys($relations));
  178. foreach ($updates as $column => $value) {
  179. /* @var EloquentModel $model */
  180. $model->setAttribute($column, $value);
  181. }
  182. $result = $model->update();
  183. $this->updateRelation($form, $model, $relations);
  184. });
  185. return $result;
  186. }
  187. /**
  188. * Swaps the order of this model with the model 'above' this model.
  189. *
  190. * @return bool
  191. */
  192. public function moveOrderUp()
  193. {
  194. $model = $this->eloquent();
  195. if ($model instanceof Sortable) {
  196. $model->moveOrderUp();
  197. return true;
  198. }
  199. return false;
  200. }
  201. /**
  202. * Swaps the order of this model with the model 'below' this model.
  203. *
  204. * @return bool
  205. */
  206. public function moveOrderDown()
  207. {
  208. $model = $this->eloquent();
  209. if ($model instanceof Sortable) {
  210. $model->moveOrderDown();
  211. return true;
  212. }
  213. return false;
  214. }
  215. /**
  216. * Destroy data.
  217. *
  218. * @param Form $form
  219. * @return bool
  220. */
  221. public function destroy(Form $form, array $deletingData)
  222. {
  223. $id = $form->getKey();
  224. $deletingData = collect($deletingData)->keyBy($this->getKeyName());
  225. collect(explode(',', $id))->filter()->each(function ($id) use ($form, $deletingData) {
  226. $data = $deletingData->get($id, []);
  227. if (!$data) return;
  228. $model = $this->createEloquent($data);
  229. $model->exists = true;
  230. if ($this->isSoftDeletes && $model->trashed()) {
  231. $form->deleteFiles($data, true);
  232. $model->forceDelete();
  233. return;
  234. }
  235. $form->deleteFiles($data);
  236. $model->delete();
  237. });
  238. return true;
  239. }
  240. /**
  241. * @param Form $form
  242. * @return array
  243. */
  244. public function getDataWhenDeleting(Form $form): array
  245. {
  246. $model = $this->eloquent();
  247. if ($this->isSoftDeletes) {
  248. $model = $model->withTrashed();
  249. }
  250. $builder = $model->newQuery();
  251. $id = $form->getKey();
  252. return $builder
  253. ->with($this->getRelations($form))
  254. ->findOrFail(
  255. collect(explode(',', $id))->filter()->toArray(),
  256. $this->getFormColumns()
  257. )
  258. ->toArray();
  259. }
  260. /**
  261. * Get the eloquent model
  262. *
  263. * @return EloquentModel
  264. */
  265. public function eloquent()
  266. {
  267. return $this->model ?: ($this->model = $this->createEloquent());
  268. }
  269. /**
  270. * @param array $data
  271. * @return EloquentModel
  272. */
  273. public function createEloquent(array $data = [])
  274. {
  275. $model = new $this->eloquentClass;
  276. if ($data) {
  277. $model->forceFill($data);
  278. }
  279. return $model;
  280. }
  281. /**
  282. * Get all relations of model from callable.
  283. *
  284. * @return array
  285. */
  286. protected function getRelations($builder)
  287. {
  288. $relations = $columns = [];
  289. if ($builder instanceof Form) {
  290. /** @var Form\Field $field */
  291. foreach ($builder->builder()->fields() as $field) {
  292. $columns[] = $field->column();
  293. }
  294. } elseif ($builder instanceof Show) {
  295. /** @var Show\Field $field */
  296. foreach ($builder->getFields() as $field) {
  297. $columns[] = $field->getName();
  298. }
  299. }
  300. $model = $this->eloquent();
  301. foreach (Arr::flatten($columns) as $column) {
  302. if (Str::contains($column, '.')) {
  303. list($relation) = explode('.', $column);
  304. if (method_exists($model, $relation) &&
  305. $model->$relation() instanceof Relations\Relation
  306. ) {
  307. $relations[] = $relation;
  308. }
  309. } elseif (method_exists($model, $column) &&
  310. !method_exists(EloquentModel::class, $column)
  311. ) {
  312. $relations[] = $column;
  313. }
  314. }
  315. return array_unique($relations);
  316. }
  317. /**
  318. * Get inputs for relations.
  319. *
  320. * @param EloquentModel $model
  321. * @param array $inputs
  322. *
  323. * @return array
  324. */
  325. protected function getRelationInputs($model, $inputs = [])
  326. {
  327. $relations = [];
  328. foreach ($inputs as $column => $value) {
  329. if (method_exists($model, $column)) {
  330. $relation = call_user_func([$model, $column]);
  331. if ($relation instanceof Relations\Relation) {
  332. $relations[$column] = $value;
  333. }
  334. }
  335. }
  336. return $relations;
  337. }
  338. /**
  339. * Update relation data.
  340. *
  341. * @param array $relationsData
  342. *
  343. * @return void
  344. */
  345. protected function updateRelation(Form $form, EloquentModel $model, $relationsData)
  346. {
  347. foreach ($relationsData as $name => $values) {
  348. if (!method_exists($model, $name)) {
  349. continue;
  350. }
  351. $relation = $model->$name();
  352. $oneToOneRelation = $relation instanceof Relations\HasOne
  353. || $relation instanceof Relations\MorphOne
  354. || $relation instanceof Relations\BelongsTo;
  355. $prepared = $form->prepareUpdate([$name => $values], $oneToOneRelation);
  356. if (empty($prepared)) {
  357. continue;
  358. }
  359. switch (true) {
  360. case $relation instanceof Relations\BelongsToMany:
  361. case $relation instanceof Relations\MorphToMany:
  362. if (isset($prepared[$name])) {
  363. $relation->sync($prepared[$name]);
  364. }
  365. break;
  366. case $relation instanceof Relations\HasOne:
  367. $related = $model->$name;
  368. // if related is empty
  369. if (is_null($related)) {
  370. $related = $relation->getRelated();
  371. $qualifiedParentKeyName = $relation->getQualifiedParentKeyName();
  372. $localKey = Arr::last(explode('.', $qualifiedParentKeyName));
  373. $related->{$relation->getForeignKeyName()} = $model->{$localKey};
  374. }
  375. foreach ($prepared[$name] as $column => $value) {
  376. $related->setAttribute($column, $value);
  377. }
  378. $related->save();
  379. break;
  380. case $relation instanceof Relations\BelongsTo:
  381. $parent = $model->$name;
  382. // if related is empty
  383. if (is_null($parent)) {
  384. $parent = $relation->getRelated();
  385. }
  386. foreach ($prepared[$name] as $column => $value) {
  387. $parent->setAttribute($column, $value);
  388. }
  389. $parent->save();
  390. // When in creating, associate two models
  391. if (!$model->{$relation->getForeignKey()}) {
  392. $model->{$relation->getForeignKey()} = $parent->getKey();
  393. $model->save();
  394. }
  395. break;
  396. case $relation instanceof Relations\MorphOne:
  397. $related = $model->$name;
  398. if (is_null($related)) {
  399. $related = $relation->make();
  400. }
  401. foreach ($prepared[$name] as $column => $value) {
  402. $related->setAttribute($column, $value);
  403. }
  404. $related->save();
  405. break;
  406. case $relation instanceof Relations\HasMany:
  407. case $relation instanceof Relations\MorphMany:
  408. foreach ($prepared[$name] as $related) {
  409. /** @var Relations\Relation $relation */
  410. $relation = $model->$name();
  411. $keyName = $relation->getRelated()->getKeyName();
  412. $instance = $relation->findOrNew(Arr::get($related, $keyName));
  413. if ($related[Form::REMOVE_FLAG_NAME] == 1) {
  414. $instance->delete();
  415. continue;
  416. }
  417. Arr::forget($related, Form::REMOVE_FLAG_NAME);
  418. $instance->fill($related);
  419. $instance->save();
  420. }
  421. break;
  422. }
  423. }
  424. }
  425. }