EloquentRepository.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. <?php
  2. namespace Dcat\Admin\Repositories;
  3. use Dcat\Admin\Contracts\TreeRepository;
  4. use Dcat\Admin\Form;
  5. use Dcat\Admin\Grid;
  6. use Dcat\Admin\Show;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Database\Eloquent\Model as EloquentModel;
  9. use Illuminate\Database\Eloquent\Relations;
  10. use Illuminate\Database\Eloquent\SoftDeletes;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Collection;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Str;
  15. use Spatie\EloquentSortable\Sortable;
  16. class EloquentRepository extends Repository implements TreeRepository
  17. {
  18. /**
  19. * @var string
  20. */
  21. protected $eloquentClass;
  22. /**
  23. * @var EloquentModel
  24. */
  25. protected $model;
  26. /**
  27. * @var Builder
  28. */
  29. protected $queryBuilder;
  30. /**
  31. * @var array
  32. */
  33. protected $relations = [];
  34. /**
  35. * EloquentRepository constructor.
  36. *
  37. * @param EloquentModel|array|string $modelOrRelations $modelOrRelations
  38. */
  39. public function __construct($modelOrRelations = [])
  40. {
  41. $this->initModel($modelOrRelations);
  42. }
  43. /**
  44. * Init model.
  45. *
  46. * @param EloquentModel|Builder|array|string $modelOrRelations
  47. */
  48. protected function initModel($modelOrRelations)
  49. {
  50. if (is_string($modelOrRelations) && class_exists($modelOrRelations)) {
  51. $this->eloquentClass = $modelOrRelations;
  52. } elseif ($modelOrRelations instanceof EloquentModel) {
  53. $this->eloquentClass = get_class($modelOrRelations);
  54. $this->model = $modelOrRelations;
  55. } elseif ($modelOrRelations instanceof Builder) {
  56. $this->model = $modelOrRelations->getModel();
  57. $this->eloquentClass = get_class($this->model);
  58. $this->queryBuilder = $modelOrRelations;
  59. } else {
  60. $this->with($modelOrRelations);
  61. }
  62. $this->setKeyName($this->eloquent()->getKeyName());
  63. $this->setIsSoftDeletes(
  64. in_array(SoftDeletes::class, class_uses($this->eloquent()))
  65. );
  66. }
  67. /**
  68. * @return string
  69. */
  70. public function getCreatedAtColumn()
  71. {
  72. return $this->eloquent()->getCreatedAtColumn();
  73. }
  74. /**
  75. * @return string
  76. */
  77. public function getUpdatedAtColumn()
  78. {
  79. return $this->eloquent()->getUpdatedAtColumn();
  80. }
  81. /**
  82. * Get columns of the grid.
  83. *
  84. * @return array
  85. */
  86. public function getGridColumns()
  87. {
  88. return ['*'];
  89. }
  90. /**
  91. * Get columns of the form.
  92. *
  93. * @return array
  94. */
  95. public function getFormColumns()
  96. {
  97. return ['*'];
  98. }
  99. /**
  100. * Get columns of the detail view.
  101. *
  102. * @return array
  103. */
  104. public function getDetailColumns()
  105. {
  106. return ['*'];
  107. }
  108. /**
  109. * Set the relationships that should be eager loaded.
  110. *
  111. * @param mixed $relations
  112. *
  113. * @return $this
  114. */
  115. public function with($relations)
  116. {
  117. $this->relations = (array) $relations;
  118. return $this;
  119. }
  120. /**
  121. * Get the grid data.
  122. *
  123. * @param Grid\Model $model
  124. *
  125. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Collection|array
  126. */
  127. public function get(Grid\Model $model)
  128. {
  129. $query = $this->newQuery();
  130. if ($this->relations) {
  131. $query->with($this->relations);
  132. }
  133. $model->getQueries()->unique()->each(function ($value) use (&$query) {
  134. if ($value['method'] == 'paginate') {
  135. $value['arguments'][1] = $this->getGridColumns();
  136. } elseif ($value['method'] == 'get') {
  137. $value['arguments'] = $this->getGridColumns();
  138. }
  139. $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
  140. });
  141. return $query;
  142. }
  143. /**
  144. * Get data to build edit form.
  145. *
  146. * @param Form $form
  147. *
  148. * @return array
  149. */
  150. public function edit(Form $form): array
  151. {
  152. $query = $this->newQuery();
  153. if ($this->isSoftDeletes) {
  154. $query->withTrashed();
  155. }
  156. $this->model = $query
  157. ->with($this->getRelations($form))
  158. ->findOrFail($form->key(), $this->getFormColumns());
  159. return $this->model->toArray();
  160. }
  161. /**
  162. * Get detail data.
  163. *
  164. * @param Show $show
  165. *
  166. * @return array
  167. */
  168. public function detail(Show $show): array
  169. {
  170. $query = $this->newQuery();
  171. if ($this->isSoftDeletes) {
  172. $query->withTrashed();
  173. }
  174. $this->model = $query
  175. ->with($this->getRelations($show))
  176. ->findOrFail($show->key(), $this->getDetailColumns());
  177. return $this->model->toArray();
  178. }
  179. /**
  180. * Store a new record.
  181. *
  182. * @param Form $form
  183. *
  184. * @return mixed
  185. */
  186. public function store(Form $form)
  187. {
  188. $result = null;
  189. DB::transaction(function () use ($form, &$result) {
  190. $model = $this->eloquent();
  191. $updates = $form->updates();
  192. [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);
  193. if ($relations) {
  194. $updates = Arr::except($updates, array_keys($relationKeyMap));
  195. }
  196. foreach ($updates as $column => $value) {
  197. $model->setAttribute($column, $value);
  198. }
  199. $result = $model->save();
  200. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  201. });
  202. return $this->eloquent()->getKey();
  203. }
  204. /**
  205. * Get data before update.
  206. *
  207. * @param Form $form
  208. *
  209. * @return array
  210. */
  211. public function getDataWhenUpdating(Form $form): array
  212. {
  213. return $this->edit($form);
  214. }
  215. /**
  216. * Update form data.
  217. *
  218. * @param Form $form
  219. *
  220. * @return bool
  221. */
  222. public function update(Form $form)
  223. {
  224. /* @var EloquentModel $builder */
  225. $model = $this->eloquent();
  226. if (! $model->getKey()) {
  227. $model->exists = true;
  228. $model->setAttribute($model->getKeyName(), $form->key());
  229. }
  230. $result = null;
  231. DB::transaction(function () use ($form, $model, &$result) {
  232. $updates = $form->updates();
  233. [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);
  234. if ($relations) {
  235. $updates = Arr::except($updates, array_keys($relationKeyMap));
  236. }
  237. foreach ($updates as $column => $value) {
  238. /* @var EloquentModel $model */
  239. $model->setAttribute($column, $value);
  240. }
  241. $result = $model->update();
  242. $this->updateRelation($form, $model, $relations, $relationKeyMap);
  243. });
  244. return $result;
  245. }
  246. /**
  247. * Swaps the order of this model with the model 'above' this model.
  248. *
  249. * @return bool
  250. */
  251. public function moveOrderUp()
  252. {
  253. $model = $this->eloquent();
  254. if ($model instanceof Sortable) {
  255. $model->moveOrderUp();
  256. return true;
  257. }
  258. return false;
  259. }
  260. /**
  261. * Swaps the order of this model with the model 'below' this model.
  262. *
  263. * @return bool
  264. */
  265. public function moveOrderDown()
  266. {
  267. $model = $this->eloquent();
  268. if ($model instanceof Sortable) {
  269. $model->moveOrderDown();
  270. return true;
  271. }
  272. return false;
  273. }
  274. /**
  275. * Destroy data.
  276. *
  277. * @param Form $form
  278. *
  279. * @return bool
  280. */
  281. public function destroy(Form $form, array $deletingData)
  282. {
  283. $id = $form->key();
  284. $deletingData = collect($deletingData)->keyBy($this->getKeyName());
  285. collect(explode(',', $id))->filter()->each(function ($id) use ($form, $deletingData) {
  286. $data = $deletingData->get($id, []);
  287. if (! $data) {
  288. return;
  289. }
  290. $model = $this->createEloquent($data);
  291. $model->exists = true;
  292. if ($this->isSoftDeletes && $model->trashed()) {
  293. $form->deleteFiles($data, true);
  294. $model->forceDelete();
  295. return;
  296. }
  297. $form->deleteFiles($data);
  298. $model->delete();
  299. });
  300. return true;
  301. }
  302. /**
  303. * @param Form $form
  304. *
  305. * @return array
  306. */
  307. public function getDataWhenDeleting(Form $form): array
  308. {
  309. $query = $this->newQuery();
  310. if ($this->isSoftDeletes) {
  311. $query->withTrashed();
  312. }
  313. $id = $form->key();
  314. return $query
  315. ->with($this->getRelations($form))
  316. ->findOrFail(
  317. collect(explode(',', $id))->filter()->toArray(),
  318. $this->getFormColumns()
  319. )
  320. ->toArray();
  321. }
  322. /**
  323. * @return string
  324. */
  325. public function getParentColumn()
  326. {
  327. return $this->eloquent()->getParentColumn();
  328. }
  329. /**
  330. * Get title column.
  331. *
  332. * @return string
  333. */
  334. public function getTitleColumn()
  335. {
  336. return $this->eloquent()->getTitleColumn();
  337. }
  338. /**
  339. * Get order column name.
  340. *
  341. * @return string
  342. */
  343. public function getOrderColumn()
  344. {
  345. return $this->eloquent()->getOrderColumn();
  346. }
  347. /**
  348. * Save tree order from a tree like array.
  349. *
  350. * @param array $tree
  351. * @param int $parentId
  352. */
  353. public function saveOrder($tree = [], $parentId = 0)
  354. {
  355. $this->eloquent()->saveOrder($tree, $parentId);
  356. }
  357. /**
  358. * Set query callback to model.
  359. *
  360. * @param \Closure|null $query
  361. *
  362. * @return $this
  363. */
  364. public function withQuery($queryCallback)
  365. {
  366. $this->eloquent()->withQuery($queryCallback);
  367. return $this;
  368. }
  369. /**
  370. * Format data to tree like array.
  371. *
  372. * @return array
  373. */
  374. public function toTree()
  375. {
  376. if ($this->relations) {
  377. $this->withQuery(function ($model) {
  378. return $model->with($this->relations);
  379. });
  380. }
  381. return $this->eloquent()->toTree();
  382. }
  383. /**
  384. * @return Builder
  385. */
  386. protected function newQuery()
  387. {
  388. if ($this->queryBuilder) {
  389. return clone $this->queryBuilder;
  390. }
  391. return $this->eloquent()->newQuery();
  392. }
  393. /**
  394. * Get the eloquent model.
  395. *
  396. * @return EloquentModel
  397. */
  398. public function eloquent()
  399. {
  400. return $this->model ?: ($this->model = $this->createEloquent());
  401. }
  402. /**
  403. * @param array $data
  404. *
  405. * @return EloquentModel
  406. */
  407. public function createEloquent(array $data = [])
  408. {
  409. $model = new $this->eloquentClass();
  410. if ($data) {
  411. $model->forceFill($data);
  412. }
  413. return $model;
  414. }
  415. /**
  416. * Get all relations of model from callable.
  417. *
  418. * @return array
  419. */
  420. protected function getRelations($builder)
  421. {
  422. $relations = $columns = [];
  423. if ($builder instanceof Form) {
  424. /** @var Form\Field $field */
  425. foreach ($builder->builder()->fields() as $field) {
  426. $columns[] = $field->column();
  427. }
  428. } elseif ($builder instanceof Show) {
  429. /** @var Show\Field $field */
  430. foreach ($builder->fields() as $field) {
  431. $columns[] = $field->getName();
  432. }
  433. }
  434. $model = $this->eloquent();
  435. foreach (Arr::flatten($columns) as $column) {
  436. if (Str::contains($column, '.')) {
  437. [$relation] = explode('.', $column);
  438. if (method_exists($model, $relation) &&
  439. $model->$relation() instanceof Relations\Relation
  440. ) {
  441. $relations[] = $relation;
  442. }
  443. } elseif (method_exists($model, $column) &&
  444. ! method_exists(EloquentModel::class, $column)
  445. ) {
  446. $relations[] = $column;
  447. }
  448. }
  449. return array_unique(array_merge($relations, $this->relations));
  450. }
  451. /**
  452. * Get inputs for relations.
  453. *
  454. * @param EloquentModel $model
  455. * @param array $inputs
  456. *
  457. * @return array
  458. */
  459. protected function getRelationInputs($model, $inputs = [])
  460. {
  461. $map = [];
  462. $relations = [];
  463. foreach ($inputs as $column => $value) {
  464. $relationColumn = null;
  465. if (method_exists($model, $column)) {
  466. $relationColumn = $column;
  467. } elseif (method_exists($model, $camelColumn = Str::camel($column))) {
  468. $relationColumn = $camelColumn;
  469. }
  470. if (! $relationColumn) {
  471. continue;
  472. }
  473. $relation = call_user_func([$model, $relationColumn]);
  474. if ($relation instanceof Relations\Relation) {
  475. $relations[$column] = $value;
  476. $map[$column] = $relationColumn;
  477. }
  478. }
  479. return [&$relations, $map];
  480. }
  481. /**
  482. * Update relation data.
  483. *
  484. * @param Form $form
  485. * @param EloquentModel $model
  486. * @param array $relationsData
  487. * @param array $relationKeyMap
  488. *
  489. * @throws \Exception
  490. */
  491. protected function updateRelation(Form $form, EloquentModel $model, array $relationsData, array $relationKeyMap)
  492. {
  493. foreach ($relationsData as $name => $values) {
  494. $relationName = $relationKeyMap[$name];
  495. if (! method_exists($model, $relationName)) {
  496. continue;
  497. }
  498. $relation = $model->$relationName();
  499. $oneToOneRelation = $relation instanceof Relations\HasOne
  500. || $relation instanceof Relations\MorphOne
  501. || $relation instanceof Relations\BelongsTo;
  502. $prepared = $form->prepareUpdate([$name => $values], $oneToOneRelation);
  503. if (empty($prepared)) {
  504. continue;
  505. }
  506. switch (true) {
  507. case $relation instanceof Relations\BelongsToMany:
  508. case $relation instanceof Relations\MorphToMany:
  509. if (isset($prepared[$name])) {
  510. $relation->sync($prepared[$name]);
  511. }
  512. break;
  513. case $relation instanceof Relations\HasOne:
  514. $related = $model->$name;
  515. // if related is empty
  516. if (is_null($related)) {
  517. $related = $relation->getRelated();
  518. $qualifiedParentKeyName = $relation->getQualifiedParentKeyName();
  519. $localKey = Arr::last(explode('.', $qualifiedParentKeyName));
  520. $related->{$relation->getForeignKeyName()} = $model->{$localKey};
  521. }
  522. foreach ($prepared[$name] as $column => $value) {
  523. $related->setAttribute($column, $value);
  524. }
  525. $related->save();
  526. break;
  527. case $relation instanceof Relations\BelongsTo:
  528. $parent = $model->$name;
  529. // if related is empty
  530. if (is_null($parent)) {
  531. $parent = $relation->getRelated();
  532. }
  533. foreach ($prepared[$name] as $column => $value) {
  534. $parent->setAttribute($column, $value);
  535. }
  536. $parent->save();
  537. // When in creating, associate two models
  538. if (! $model->{$relation->getForeignKey()}) {
  539. $model->{$relation->getForeignKey()} = $parent->getKey();
  540. $model->save();
  541. }
  542. break;
  543. case $relation instanceof Relations\MorphOne:
  544. $related = $model->$name;
  545. if (is_null($related)) {
  546. $related = $relation->make();
  547. }
  548. foreach ($prepared[$name] as $column => $value) {
  549. $related->setAttribute($column, $value);
  550. }
  551. $related->save();
  552. break;
  553. case $relation instanceof Relations\HasMany:
  554. case $relation instanceof Relations\MorphMany:
  555. foreach ($prepared[$name] as $related) {
  556. /** @var Relations\Relation $relation */
  557. $relation = $model->$relationName();
  558. $keyName = $relation->getRelated()->getKeyName();
  559. $instance = $relation->findOrNew(Arr::get($related, $keyName));
  560. if ($related[Form::REMOVE_FLAG_NAME] == 1) {
  561. $instance->delete();
  562. continue;
  563. }
  564. Arr::forget($related, Form::REMOVE_FLAG_NAME);
  565. $instance->fill($related);
  566. $instance->save();
  567. }
  568. break;
  569. }
  570. }
  571. }
  572. }