EloquentRepository.php 14 KB

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