Sfoglia il codice sorgente

优化selectOptions层级结构显示,解决前缀呈现随层级深度指数增加问题 #618

jqh 4 anni fa
parent
commit
4580b6d086
1 ha cambiato i file con 22 aggiunte e 9 eliminazioni
  1. 22 9
      src/Traits/ModelTree.php

+ 22 - 9
src/Traits/ModelTree.php

@@ -284,12 +284,14 @@ trait ModelTree
      * @param array  $nodes
      * @param int    $parentId
      * @param string $prefix
+     * @param string $space
      *
      * @return array
      */
-    protected function buildSelectOptions($nodes = [], $parentId = 0, $prefix = '')
+    protected function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '', $space = ' ')
     {
-        $prefix = $prefix ?: str_repeat(' ', 6);
+        $d = '├─';
+        $prefix = $prefix ?: $d.$space;
 
         $options = [];
 
@@ -297,15 +299,17 @@ trait ModelTree
             $nodes = $this->allNodes()->toArray();
         }
 
-        $titleColumn = $this->getTitleColumn();
-        $parentColumn = $this->getParentColumn();
+        foreach ($nodes as $index => $node) {
+            if ($node[$this->getParentColumn()] == $parentId) {
+                $currentPrefix = $this->hasNextSibling($nodes, $node[$this->getParentColumn()], $index) ? $prefix : str_replace($d, '└─', $prefix);
 
-        foreach ($nodes as $node) {
-            $node[$titleColumn] = $prefix.' '.$node[$titleColumn];
-            if ($node[$parentColumn] == $parentId) {
-                $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $prefix.$prefix);
+                $node[$this->getTitleColumn()] = $currentPrefix.$space.$node[$this->getTitleColumn()];
 
-                $options[$node[$this->getKeyName()]] = $node[$titleColumn];
+                $childrenPrefix = str_replace($d, str_repeat($space, 6), $prefix).$d.str_replace([$d, $space], '', $prefix);
+
+                $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $childrenPrefix);
+
+                $options[$node[$this->getKeyName()]] = $node[$this->getTitleColumn()];
 
                 if ($children) {
                     $options += $children;
@@ -316,6 +320,15 @@ trait ModelTree
         return $options;
     }
 
+    protected function hasNextSibling($nodes, $parentId, $index)
+    {
+        foreach ($nodes as $i => $node) {
+            if ($node[$this->getParentColumn()] == $parentId && $i > $index) {
+                return true;
+            }
+        }
+    }
+
     /**
      * {@inheritdoc}
      */