ModelTree.php 9.9 KB

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