ModelTree.php 9.6 KB

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