luizalbertoni/tree-parser

Parse tree structure

1.0.2 2024-01-17 12:14 UTC

This package is auto-updated.

Last update: 2024-11-17 14:43:05 UTC


README

Latest Stable Version Software License Build Status Code Coverage Scrutinizer Code Quality

Parse this:

   Root
     |- Level 1.1
       |- Level 2.1
     |- Level 1.2
       |- Level 2.2
         |- Level 3
           |- Level 4

to this:

foreach ($root->children as $child) {
    print $child->name;

    print $child->order;

    print $child->level;

    print_r($child->children);

    print_r($child->children[0]->children);

    print $child->children[0]->parent === $child;
}

Table of Content

Install

Via Composer

$ composer require baopham/tree-parser

Usage

// A tree with 2 spaces for indentation
$tree = <<<TREE
  Root
    |- Level 1 - Order 1
      |- Level 2 - Order 2
        |- Level 3 - Order 3
        |- Level 3 - Order 4
      |- Level 2 - Order 5
    |- Level 1 - Order 6
      |- Level 2 - Order 7
        |- Level 3 - Order 8
          |- Level 4 - Order 9
TREE;

$parser = new BaoPham\TreeParser($tree);

$parser->setIndentation(2); // number of spaces for an indentation, 2 is the default.

$root = $parser->parse();

foreach ($root->children as $child) {
    print $child->name;

    print $child->order;

    print $child->level;

    print_r($child->children);

    print_r($child->children[0]->children);

    print $child->children[0]->parent === $child;
}

Advanced

$tree = <<<TREE
  Root
    |- Level 1 - Order 1
      |- Level 2 - Order 2
        |- Level 3 - Order 3
        |- Level 3 - Order 4
      |- Level 2 - Order 5
    |- Level 1 - Order 6
      |- Level 2 - Order 7
        |- Level 3 - Order 8
          |- Level 4 - Order 9
TREE;

$parser = new BaoPham\TreeParser($tree);

$parser->parse();

$structure = $parser->getStructure();

// Get nodes at level 3
$level3Nodes = $structure[3];
// Get node at level 3, order 4
$node = $structure[3][4];

// Get last leaf
$orderedNodes = $parser->getOrderedNodes();
$lastLeaf = $orderedNodes[count($orderedNodes) - 1];

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Credits

License

The MIT License (MIT). Please see License File for more information.