コード例 #1
0
 /**
  * Create all of the child nodes of a root node.
  *
  * @param array $nodes
  */
 protected function createNodes($nodes)
 {
     // $parent is the array of parent nodes.
     $parent = [];
     foreach ($nodes as $load_record) {
         $match = preg_match('/^\\*+/', $load_record, $matches);
         // If there is no match then we have hit a top level category.
         // Add this to the $result array and reset the $parent array.
         if ($match === 0) {
             $node_name = trim($load_record);
             $root_node = Category::create(['name' => $node_name, 'description' => $node_name]);
             $parent = [0 => $root_node];
             continue;
         }
         // If there is a match then check how many levels deep we are.
         $levels = strlen($matches[0]);
         // Grab the node name
         $node_name = trim(substr($load_record, $levels));
         // Grab the current node at the level of the parent.
         /** @var Category $current */
         $current = $parent[$levels - 1];
         // Add this node as a child of the parent.
         $child_node = $current->children()->create(['name' => $node_name]);
         // Update the description, just for fun
         $child_node->description = $child_node->path;
         $child_node->save();
         // Store this node name as a potential future parent.
         $parent[$levels] = $child_node;
     }
 }
コード例 #2
0
 public function run()
 {
     $nodes = $this->getNodes();
     // Build the above list of nodes as a heirarchical tree
     // of categories.
     foreach ($nodes as $node_name => $node_children) {
         // Create each root node.
         $root_node = Category::create(['name' => $node_name, 'description' => $node_name]);
         // Create the children of the root node.
         if (!empty($node_children)) {
             $this->createNodes($root_node, $node_children);
         }
     }
 }