ModelTree.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. namespace Dcat\Admin\Traits;
  3. use Dcat\Admin\Exception\AdminException;
  4. use Dcat\Admin\Support\Helper;
  5. use Dcat\Admin\Tree;
  6. use Illuminate\Database\Eloquent\Builder;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Facades\Request;
  10. use Spatie\EloquentSortable\SortableTrait;
  11. /**
  12. * @property string $parentColumn
  13. * @property string $titleColumn
  14. * @property string $orderColumn
  15. * @property array $sortable
  16. */
  17. trait ModelTree
  18. {
  19. use SortableTrait;
  20. /**
  21. * @var array
  22. */
  23. protected static $branchOrder = [];
  24. /**
  25. * @var \Closure[]
  26. */
  27. protected $queryCallbacks = [];
  28. /**
  29. * @return string
  30. */
  31. public function getParentColumn()
  32. {
  33. return empty($this->parentColumn) ? 'parent_id' : $this->parentColumn;
  34. }
  35. /**
  36. * Get title column.
  37. *
  38. * @return string
  39. */
  40. public function getTitleColumn()
  41. {
  42. return empty($this->titleColumn) ? 'title' : $this->titleColumn;
  43. }
  44. /**
  45. * Get order column name.
  46. *
  47. * @return string
  48. */
  49. public function getOrderColumn()
  50. {
  51. return empty($this->orderColumn) ? 'order' : $this->orderColumn;
  52. }
  53. /**
  54. * Set query callback to model.
  55. *
  56. * @param \Closure|null $query
  57. *
  58. * @return $this
  59. */
  60. public function withQuery(\Closure $query = null)
  61. {
  62. $this->queryCallbacks[] = $query;
  63. return $this;
  64. }
  65. /**
  66. * Format data to tree like array.
  67. *
  68. * @return array
  69. */
  70. public function toTree(array $nodes = null)
  71. {
  72. if ($nodes === null) {
  73. $nodes = $this->allNodes();
  74. }
  75. return Helper::buildNestedArray(
  76. $nodes,
  77. 0,
  78. $this->getKeyName(),
  79. $this->getParentColumn()
  80. );
  81. }
  82. /**
  83. * Get all elements.
  84. *
  85. * @return static[]|\Illuminate\Support\Collection
  86. */
  87. public function allNodes()
  88. {
  89. return $this->callQueryCallbacks(new static())
  90. ->orderBy($this->getOrderColumn(), 'asc')
  91. ->get();
  92. }
  93. /**
  94. * @param $this $model
  95. *
  96. * @return $this|Builder
  97. */
  98. protected function callQueryCallbacks($model)
  99. {
  100. foreach ($this->queryCallbacks as $callback) {
  101. if ($callback) {
  102. $model = $callback($model);
  103. }
  104. }
  105. return $model;
  106. }
  107. /**
  108. * Set the order of branches in the tree.
  109. *
  110. * @param array $order
  111. *
  112. * @return void
  113. */
  114. protected static function setBranchOrder(array $order)
  115. {
  116. static::$branchOrder = array_flip(Arr::flatten($order));
  117. static::$branchOrder = array_map(function ($item) {
  118. return ++$item;
  119. }, static::$branchOrder);
  120. }
  121. /**
  122. * Save tree order from a tree like array.
  123. *
  124. * @param array $tree
  125. * @param int $parentId
  126. */
  127. public static function saveOrder($tree = [], $parentId = 0)
  128. {
  129. if (empty(static::$branchOrder)) {
  130. static::setBranchOrder($tree);
  131. }
  132. foreach ($tree as $branch) {
  133. $node = static::find($branch['id']);
  134. $node->{$node->getParentColumn()} = $parentId;
  135. $node->{$node->getOrderColumn()} = static::$branchOrder[$branch['id']];
  136. $node->save();
  137. if (isset($branch['children'])) {
  138. static::saveOrder($branch['children'], $branch['id']);
  139. }
  140. }
  141. }
  142. protected function determineOrderColumnName()
  143. {
  144. return $this->getOrderColumn();
  145. }
  146. public function moveOrderDown()
  147. {
  148. $orderColumnName = $this->determineOrderColumnName();
  149. $parentColumnName = $this->getParentColumn();
  150. $sameOrderModel = $this->getSameOrderModel('>');
  151. if ($sameOrderModel) {
  152. $this->$orderColumnName = $this->$orderColumnName + 1;
  153. $this->save();
  154. return $this;
  155. }
  156. $swapWithModel = $this->buildSortQuery()
  157. ->limit(1)
  158. ->ordered()
  159. ->where($orderColumnName, '>', $this->$orderColumnName)
  160. ->where($parentColumnName, $this->$parentColumnName)
  161. ->first();
  162. if (! $swapWithModel) {
  163. return false;
  164. }
  165. return $this->swapOrderWithModel($swapWithModel);
  166. }
  167. public function moveOrderUp()
  168. {
  169. $orderColumnName = $this->determineOrderColumnName();
  170. $parentColumnName = $this->getParentColumn();
  171. $swapWithModel = $this->buildSortQuery()
  172. ->limit(1)
  173. ->ordered('desc')
  174. ->where($orderColumnName, '<', $this->$orderColumnName)
  175. ->where($parentColumnName, $this->$parentColumnName)
  176. ->first();
  177. if ($swapWithModel) {
  178. return $this->swapOrderWithModel($swapWithModel);
  179. }
  180. $sameOrderModel = $this->getSameOrderModel('<');
  181. if (! $sameOrderModel) {
  182. return false;
  183. }
  184. $sameOrderModel->$orderColumnName = $sameOrderModel->$orderColumnName + 1;
  185. $sameOrderModel->save();
  186. return $this;
  187. }
  188. protected function getSameOrderModel(string $operator = '<')
  189. {
  190. $orderColumnName = $this->determineOrderColumnName();
  191. $parentColumnName = $this->getParentColumn();
  192. return $this->buildSortQuery()
  193. ->limit(1)
  194. ->orderBy($orderColumnName)
  195. ->orderBy($this->getKeyName())
  196. ->where($this->getKeyName(), $operator, $this->getKey())
  197. ->where($orderColumnName, $this->$orderColumnName)
  198. ->where($parentColumnName, $this->$parentColumnName)
  199. ->first();
  200. }
  201. public function moveToStart()
  202. {
  203. $parentColumnName = $this->getParentColumn();
  204. $firstModel = $this->buildSortQuery()
  205. ->limit(1)
  206. ->ordered()
  207. ->where($parentColumnName, $this->$parentColumnName)
  208. ->first();
  209. if ($firstModel->id === $this->id) {
  210. return $this;
  211. }
  212. $orderColumnName = $this->determineOrderColumnName();
  213. $this->$orderColumnName = $firstModel->$orderColumnName;
  214. $this->save();
  215. $this->buildSortQuery()->where($this->getKeyName(), '!=', $this->id)->increment($orderColumnName);
  216. return $this;
  217. }
  218. /**
  219. * Get options for Select field in form.
  220. *
  221. * @param \Closure|null $closure
  222. * @param string $rootText
  223. *
  224. * @return array
  225. */
  226. public static function selectOptions(\Closure $closure = null, $rootText = null)
  227. {
  228. $rootText = $rootText ?: admin_trans_label('root');
  229. $options = (new static())->withQuery($closure)->buildSelectOptions();
  230. return collect($options)->prepend($rootText, 0)->all();
  231. }
  232. /**
  233. * Build options of select field in form.
  234. *
  235. * @param array $nodes
  236. * @param int $parentId
  237. * @param string $prefix
  238. * @param string $space
  239. *
  240. * @return array
  241. */
  242. protected function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '', $space = '&nbsp;')
  243. {
  244. $d = '├─';
  245. $prefix = $prefix ?: $d.$space;
  246. $options = [];
  247. if (empty($nodes)) {
  248. $nodes = $this->allNodes()->toArray();
  249. }
  250. foreach ($nodes as $index => $node) {
  251. if ($node[$this->getParentColumn()] == $parentId) {
  252. $currentPrefix = $this->hasNextSibling($nodes, $node[$this->getParentColumn()], $index) ? $prefix : str_replace($d, '└─', $prefix);
  253. $node[$this->getTitleColumn()] = $currentPrefix.$space.$node[$this->getTitleColumn()];
  254. $childrenPrefix = str_replace($d, str_repeat($space, 6), $prefix).$d.str_replace([$d, $space], '', $prefix);
  255. $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $childrenPrefix);
  256. $options[$node[$this->getKeyName()]] = $node[$this->getTitleColumn()];
  257. if ($children) {
  258. $options += $children;
  259. }
  260. }
  261. }
  262. return $options;
  263. }
  264. protected function hasNextSibling($nodes, $parentId, $index)
  265. {
  266. foreach ($nodes as $i => $node) {
  267. if ($node[$this->getParentColumn()] == $parentId && $i > $index) {
  268. return true;
  269. }
  270. }
  271. }
  272. /**
  273. * {@inheritdoc}
  274. */
  275. public function delete()
  276. {
  277. $this->where($this->getParentColumn(), $this->getKey())->delete();
  278. return parent::delete();
  279. }
  280. /**
  281. * {@inheritdoc}
  282. */
  283. protected static function boot()
  284. {
  285. parent::boot();
  286. static::saving(function (Model $branch) {
  287. $parentColumn = $branch->getParentColumn();
  288. if (
  289. $branch->getKey()
  290. && Request::has($parentColumn)
  291. && Request::input($parentColumn) == $branch->getKey()
  292. ) {
  293. throw new AdminException(trans('admin.parent_select_error'));
  294. }
  295. if (Request::has(Tree::SAVE_ORDER_NAME)) {
  296. $order = Request::input(Tree::SAVE_ORDER_NAME);
  297. Request::offsetUnset(Tree::SAVE_ORDER_NAME);
  298. Tree::make(new static())->saveOrder($order);
  299. $branch->{$branch->getKeyName()} = true;
  300. return false;
  301. }
  302. return $branch;
  303. });
  304. }
  305. }