Code Monkey home page Code Monkey logo

stefano-tree's Introduction

Tree

Latest Stable Version Build Status Coverage Status Scrutinizer Code Quality License Total Downloads Monthly Downloads

Buy me a coffee

Donate on PayPal

Nested Set implementation for PHP.

Live demo

Features

  • NestedSet(MPTT - Modified Pre-order Tree Traversal)
  • Support scopes (multiple independent tree in one db table)
  • Rebuild broken tree
  • Tested with MySQL/MariaDB and PostgreSQL but should work with any database vendor which support transaction
  • Supported PDO, Zend Framework 1, Laminas Db, Doctrine 2 DBAL and Doctrine 3 DBAL. It is easy to implement support for any framework
  • Support nested transaction
  • PHP 7 and PHP 8 support

Dependencies

  • This library has no external dependencies. Can work with pure PHP.

Installation

Run following command in terminal

composer require stefano/stefano-tree

Create Tree Adapter

key type required default value note
tableName string yes
idColumnName string yes
leftColumnName string no lft
rightColumnName string no rgt
levelColumnName string no level
parentIdColumnName string no parent_id
sequenceName string see note Required for PostgreSQL
scopeColumnName string see note If empty scope support is disabled
dbSelectBuilder callable no see Join table example below
use \StefanoTree\NestedSet;

$options = array(
    'tableName'    => 'tree_traversal',
    'idColumnName' => 'tree_traversal_id',
    // other options
);

$dbAdapter = pure \PDO, Zend1 Db Adapter, Laminas Db Adapter, Doctrine DBAL Connection or any class which implements StefanoTree\NestedSet\Adapter\AdapterInterface interface 

$tree = new NestedSet($options, $dbAdapter);
  • You can join table.
$options = array(
    'tableName'       => 'tree_traversal',
    'idColumnName'    => 'tree_traversal_id',
    'dbSelectBuilder' => function() {
         // You can use any "callable" like function or object
         // Select must be without where or order part
         return 'SELECT tree_traversal.*, m.something, ...'
           .' FROM tree_traversal'
           .' LEFT JOIN metadata AS m ON tree_traversal.id=m.tree_id';
     }, 
    // other options
);

$tree = new NestedSet($options, $dbAdapter);

API

Creating nodes

  • Create root node
use StefanoTree\Exception\ValidationException;

try {
    $data = array(
        // values
        // id_column_name => uuid 
    );
    
    // create root node.
    $rootNodeId = $tree->createRootNode($data);
    
    // create root node. Second param "$scope" is required only if scope support is enabled.
    $rootNodeId = $tree->createRootNode($data, $scope);    
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}    
  • Create new node. You can create new node at 4 different locations.

placements

use StefanoTree\Exception\ValidationException;

try {
    $targetNodeId = 10;
    
    $data = array(
        // values
        // id_column_name => uuid 
    );

    $nodeId = $tree->addNode($targetNodeId, $data, $tree::PLACEMENT_CHILD_TOP);
    $nodeId = $tree->addNode($targetNodeId, $data, $tree::PLACEMENT_CHILD_BOTTOM);
    $nodeId = $tree->addNode($targetNodeId, $data, $tree::PLACEMENT_TOP);
    $nodeId = $tree->addNode($targetNodeId, $data, $tree::PLACEMENT_BOTTOM);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}    

Update Node

use StefanoTree\Exception\ValidationException;

try {
    $targetNodeId = 10;
    
    $data = array(
        // values
    );
    
    $tree->updateNode($targetNodeId, $data);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}    

Move node

  • You can move node at 4 different locations.

placements

use StefanoTree\Exception\ValidationException;

try {
    $sourceNodeId = 15;
    $targetNodeId = 10;
    
    $tree->moveNode($sourceNodeId, $targetNodeId, $tree::PLACEMENT_CHILD_TOP);
    $tree->moveNode($sourceNodeId, $targetNodeId, $tree::PLACEMENT_CHILD_BOTTOM);
    $tree->moveNode($sourceNodeId, $targetNodeId, $tree::PLACEMENT_TOP);
    $tree->moveNode($sourceNodeId, $targetNodeId, $tree::PLACEMENT_BOTTOM);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}        

Delete node or branch

use StefanoTree\Exception\ValidationException;

try {
    $nodeId = 15;
    
    $tree->deleteBranch($nodeId);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}    

Getting nodes

  • Get descendants
$nodeId = 15;

// all descendants
$tree->getDescendantsQueryBuilder()
     ->get($nodeId);
     
// all descendants result as nested array
$tree->getDescendantsQueryBuilder()
     ->get($nodeId, true);
     
// only children     
$tree->getDescendantsQueryBuilder()
     ->excludeFirstNLevel(1)
     ->levelLimit(1)
     ->get($nodeId);

// exclude first level($nodeId) from result
$tree->getDescendants()
     ->excludeFirstNLevel(1)
     ->get($nodeId);

// exclude first two levels from result
$tree->getDescendantsQueryBuilder()
     ->excludeFirstNLevel(2)
     ->get($nodeId);

// return first 4 level
$tree->getDescendantsQueryBuilder()
     ->levelLimit(4)
     ->get($nodeId);

// exclude branch from  result
$tree->getDescendantsQueryBuilder()
     ->excludeBranch(22)
     ->get($nodeId);
  • Get Ancestors
$nodeId = 15;

// get all
$tree->getAncestorsQueryBuilder()
     ->get($nodeId);
     
// get all as nested array
$tree->getAncestorsQueryBuilder()
     ->get($nodeId, true);

// exclude last node($nodeId) from result
$tree->getAncestorsQueryBuilder()
     ->excludeLastNLevel(1)
     ->get($nodeId);

// exclude first two levels from result
$tree->getAncestorsQueryBuilder()
     ->excludeFirstNLevel(2)
     ->get($nodeId);

Validation and Rebuild broken tree

  • Check if tree is valid
use StefanoTree\Exception\ValidationException;

try {
    $satus = $tree->isValid($rootNodeId);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}
  • Rebuild broken tree
use StefanoTree\Exception\ValidationException;

try {
    $tree->rebuild($rootNodeId);
} catch (ValidationException $e) {
    $errorMessage = $e->getMessage();
}

Contributing

Any contributions are welcome. If you find any issue don't hesitate to open a new issue or send a pull request.

Buy me a coffee

stefano-tree's People

Contributors

bartko-s avatar codelingobot avatar tomasfejfar avatar tsmgeek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

stefano-tree's Issues

Moving nodeitem up/down

Is there any way to move a Node up or down by X positions.
Example, changing the order of a set of child nodes you would need to move a single item up or down in a list, this could be move by X up/down within its level, not having to specify target node.

Do you have a full list of BC breaks?

I'm trying to upgrade from 2.x to 4.x and I can't find any BC breaks before 3.1 unless I search through all revisions of the update file. Is there a summary I can find somewhere? Right now I fail properly upgrading due to the lack of BC break documentation and what the replacement of those functions should be.

A Typical Data Field and Value for a Node

I've been trying to integrate this library into Joomla components.
My actual struggle is; for an example taking the following code from the documentation:

` try {
$data = array(
// values
// id_column_name => uuid
);

 // create root node.
 $rootNodeId = $tree->createRootNode($data);  
 // create root node. Second param "$scope" is required only if scope support is enabled.
 $rootNodeId = $tree->createRootNode($data, $scope);    
 } catch (ValidationException $e) {
 $errorMessage = $e->getMessage();
  } `

what is going to be the values for this section
$data = array( // values // id_column_name => uuid );

if my database table has these columns
'tableName' => 'vz0q4_users', 'idColumnName' => 'id', 'sequenceName' => 'categories', 'scopeColumnName' => 'scope', 'leftColumnName' => 'lft', 'rightColumnName' => 'rght', 'levelColumnName' => 'level', 'parentIdColumnName' => 'parent_id'

Thank you.

Softdelete behaviar

Any guide for using soft delete behavior in data ?

Show all, or show just Undeleted for tree results.

Thanks for awesome and useful project btw ๐Ÿ‘

Simplify NestedSet::__construct

Although it says in the README that it doesn't have any dependencies, the way it's today, it needs Doctrine and Zend\Db. It needs to be installed to be able to use the NestedSet class. I think that class only needs to get an instance of an AdapterInterface and everything else should be handled outside of this class.

What do you think?

Add Phalcon support

Could you please support Phalcon so we can use models instead of using direct database access ?

What is the scope and the target?

Hi,
I have few questions.
What is a scope?
Is there a way to have many root nodes?
When you move a node, will the "target" be the new parentId?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.