- md5
- e3e4d7d9f377342a18cd48dd79dd92fd
- sha1
- fd20e9708608d442bef32ded387813cf891511ef
- sha256
- 811bffe640e3737143e38ffbd0b992b4113048e24a25523a88f41447b12c840f
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211
<?php
/**
* @package FrameworkOnFramework
* @subpackage table
* @copyright Copyright (C) 2010 - 2015 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// Protect from unauthorized access
defined('FOF_INCLUDED') or die;
/**
* A class to manage tables holding nested sets (hierarchical data)
*
* @property int $lft Left value (for nested set implementation)
* @property int $rgt Right value (for nested set implementation)
* @property string $hash Slug hash (optional; for faster searching)
* @property string $slug Node's slug (optional)
* @property string $title Title of the node (optional)
*/
class FOFTableNested extends FOFTable
{
/** @var int The level (depth) of this node in the tree */
protected $treeDepth = null;
/** @var FOFTableNested The root node in the tree */
protected $treeRoot = null;
/** @var FOFTableNested The parent node of ourselves */
protected $treeParent = null;
/** @var bool Should I perform a nested get (used to query ascendants/descendants) */
protected $treeNestedGet = false;
/** @var array A collection of custom, additional where clauses to apply during buildQuery */
protected $whereClauses = array();
/**
* Public constructor. Overrides the parent constructor, making sure there are lft/rgt columns which make it
* compatible with nested sets.
*
* @param string $table Name of the database table to model.
* @param string $key Name of the primary key field in the table.
* @param JDatabaseDriver &$db Database driver
* @param array $config The configuration parameters array
*
* @throws \RuntimeException When lft/rgt columns are not found
*/
public function __construct($table, $key, &$db, $config = array())
{
parent::__construct($table, $key, $db, $config);
if (!$this->hasField('lft') || !$this->hasField('rgt'))
{
throw new \RuntimeException("Table " . $this->getTableName() . " is not compatible with FOFTableNested: it does not have lft/rgt columns");
}
}
/**
* Overrides the automated table checks to handle the 'hash' column for faster searching
*
* @return boolean
*/
public function check()
{
// Create a slug if there is a title and an empty slug
if ($this->hasField('title') && $this->hasField('slug') && empty($this->slug))
{
$this->slug = FOFStringUtils::toSlug($this->title);
}
// Create the SHA-1 hash of the slug for faster searching (make sure the hash column is CHAR(64) to take
// advantage of MySQL's optimised searching for fixed size CHAR columns)
if ($this->hasField('hash') && $this->hasField('slug'))
{
$this->hash = sha1($this->slug);
}
// Reset cached values
$this->resetTreeCache();
return parent::check();
}
/**
* Delete a node, either the currently loaded one or the one specified in $id. If an $id is specified that node
* is loaded before trying to delete it. In the end the data model is reset. If the node has any children nodes
* they will be removed before the node itself is deleted.
*
* @param integer $oid The primary key value of the item to delete
*
* @throws UnexpectedValueException
*
* @return boolean True on success
*/
public function delete($oid = null)
{
// Load the specified record (if necessary)
if (!empty($oid))
{
$this->load($oid);
}
$k = $this->_tbl_key;
$pk = (!$oid) ? $this->$k : $oid;
// If no primary key is given, return false.
if (!$pk)
{
throw new UnexpectedValueException('Null primary key not allowed.');
}
// Execute the logic only if I have a primary key, otherwise I could have weird results
// Perform the checks on the current node *BEFORE* starting to delete the children
if (!$this->onBeforeDelete($oid))
{
return false;
}
$result = true;
// Recursively delete all children nodes as long as we are not a leaf node and $recursive is enabled
if (!$this->isLeaf())
{
// Get all sub-nodes
$table = $this->getClone();
$table->bind($this->getData());
$subNodes = $table->getDescendants();
// Delete all subnodes (goes through the model to trigger the observers)
if (!empty($subNodes))
{
/** @var FOFTableNested $item */
foreach ($subNodes as $item)
{
// We have to pass the id, so we are getting it again from the database.
// We have to do in this way, since a previous child could have changed our lft and rgt values
if(!$item->delete($item->$k))
{
// A subnode failed or prevents the delete, continue deleting other nodes,
// but preserve the current node (ie the parent)
$result = false;
}
};
// Load it again, since while deleting a children we could have updated ourselves, too
$this->load($pk);
}
}
if($result)
{
// Delete the row by primary key.
$query = $this->_db->getQuery(true);
$query->delete();
$query->from($this->_tbl);
$query->where($this->_tbl_key . ' = ' . $this->_db->q($pk));
$this->_db->setQuery($query)->execute();
$result = $this->onAfterDelete($oid);
}
return $result;
}
protected function onAfterDelete($oid)
{
$db = $this->getDbo();
$myLeft = $this->lft;
$myRight = $this->rgt;
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
// Move all siblings to the left
$width = $this->rgt - $this->lft + 1;
// Wrap everything in a transaction
$db->transactionStart();
try
{
// Shrink lft values
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldLft . ' = ' . $fldLft . ' - '.$width)
->where($fldLft . ' > ' . $db->q($myLeft));
$db->setQuery($query)->execute();
// Shrink rgt values
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldRgt . ' = ' . $fldRgt . ' - '.$width)
->where($fldRgt . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
// Roll back the transaction on error
$db->transactionRollback();
throw $e;
}
return parent::onAfterDelete($oid);
}
/**
* Not supported in nested sets
*
* @param string $where Ignored
*
* @return void
*
* @throws RuntimeException
*/
public function reorder($where = '')
{
throw new RuntimeException('reorder() is not supported by FOFTableNested');
}
/**
* Not supported in nested sets
*
* @param integer $delta Ignored
* @param string $where Ignored
*
* @return void
*
* @throws RuntimeException
*/
public function move($delta, $where = '')
{
throw new RuntimeException('move() is not supported by FOFTableNested');
}
/**
* Create a new record with the provided data. It is inserted as the last child of the current node's parent
*
* @param array $data The data to use in the new record
*
* @return static The new node
*/
public function create($data)
{
$newNode = $this->getClone();
$newNode->reset();
$newNode->bind($data);
if ($this->isRoot())
{
return $newNode->insertAsChildOf($this);
}
else
{
return $newNode->insertAsChildOf($this->getParent());
}
}
/**
* Makes a copy of the record, inserting it as the last child of the given node's parent.
*
* @param integer|array $cid The primary key value (or values) or the record(s) to copy.
* If null, the current record will be copied
*
* @return self|FOFTableNested The last copied node
*/
public function copy($cid = null)
{
//We have to cast the id as array, or the helper function will return an empty set
if($cid)
{
$cid = (array) $cid;
}
FOFUtilsArray::toInteger($cid);
$k = $this->_tbl_key;
if (count($cid) < 1)
{
if ($this->$k)
{
$cid = array($this->$k);
}
else
{
// Even if it's null, let's still create the record
$this->create($this->getData());
return $this;
}
}
foreach ($cid as $item)
{
// Prevent load with id = 0
if (!$item)
{
continue;
}
$this->load($item);
$this->create($this->getData());
}
return $this;
}
/**
* Method to reset class properties to the defaults set in the class
* definition. It will ignore the primary key as well as any private class
* properties.
*
* @return void
*/
public function reset()
{
$this->resetTreeCache();
parent::reset();
}
/**
* Insert the current node as a tree root. It is a good idea to never use this method, instead providing a root node
* in your schema installation and then sticking to only one root.
*
* @return self
*/
public function insertAsRoot()
{
// You can't insert a node that is already saved i.e. the table has an id
if($this->getId())
{
throw new RuntimeException(__METHOD__.' can be only used with new nodes');
}
// First we need to find the right value of the last parent, a.k.a. the max(rgt) of the table
$db = $this->getDbo();
// Get the lft/rgt names
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$query = $db->getQuery(true)
->select('MAX(' . $fldRgt . ')')
->from($db->qn($this->getTableName()));
$maxRgt = $db->setQuery($query, 0, 1)->loadResult();
if (empty($maxRgt))
{
$maxRgt = 0;
}
$this->lft = ++$maxRgt;
$this->rgt = ++$maxRgt;
$this->store();
return $this;
}
/**
* Insert the current node as the first (leftmost) child of a parent node.
*
* WARNING: If it's an existing node it will be COPIED, not moved.
*
* @param FOFTableNested $parentNode The node which will become our parent
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function insertAsFirstChildOf(FOFTableNested &$parentNode)
{
if($parentNode->lft >= $parentNode->rgt)
{
throw new RuntimeException('Invalid position values for the parent node');
}
// Get a reference to the database
$db = $this->getDbo();
// Get the field names
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$fldLft = $db->qn($this->getColumnAlias('lft'));
// Nullify the PK, so a new record will be created
$pk = $this->getKeyName();
$this->$pk = null;
// Get the value of the parent node's rgt
$myLeft = $parentNode->lft;
// Update my lft/rgt values
$this->lft = $myLeft + 1;
$this->rgt = $myLeft + 2;
// Update parent node's right (we added two elements in there, remember?)
$parentNode->rgt += 2;
// Wrap everything in a transaction
$db->transactionStart();
try
{
// Make a hole (2 queries)
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldLft . ' = ' . $fldLft . '+2')
->where($fldLft . ' > ' . $db->q($myLeft));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldRgt . ' = ' . $fldRgt . '+ 2')
->where($fldRgt . '>' . $db->q($myLeft));
$db->setQuery($query)->execute();
// Insert the new node
$this->store();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
// Roll back the transaction on error
$db->transactionRollback();
throw $e;
}
return $this;
}
/**
* Insert the current node as the last (rightmost) child of a parent node.
*
* WARNING: If it's an existing node it will be COPIED, not moved.
*
* @param FOFTableNested $parentNode The node which will become our parent
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function insertAsLastChildOf(FOFTableNested &$parentNode)
{
if($parentNode->lft >= $parentNode->rgt)
{
throw new RuntimeException('Invalid position values for the parent node');
}
// Get a reference to the database
$db = $this->getDbo();
// Get the field names
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$fldLft = $db->qn($this->getColumnAlias('lft'));
// Nullify the PK, so a new record will be created
$pk = $this->getKeyName();
$this->$pk = null;
// Get the value of the parent node's lft
$myRight = $parentNode->rgt;
// Update my lft/rgt values
$this->lft = $myRight;
$this->rgt = $myRight + 1;
// Update parent node's right (we added two elements in there, remember?)
$parentNode->rgt += 2;
// Wrap everything in a transaction
$db->transactionStart();
try
{
// Make a hole (2 queries)
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldRgt . ' = ' . $fldRgt . '+2')
->where($fldRgt . '>=' . $db->q($myRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldLft . ' = ' . $fldLft . '+2')
->where($fldLft . '>' . $db->q($myRight));
$db->setQuery($query)->execute();
// Insert the new node
$this->store();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
// Roll back the transaction on error
$db->transactionRollback();
throw $e;
}
return $this;
}
/**
* Alias for insertAsLastchildOf
*
* @codeCoverageIgnore
* @param FOFTableNested $parentNode
*
* @return $this for chaining
*
* @throws Exception
*/
public function insertAsChildOf(FOFTableNested &$parentNode)
{
return $this->insertAsLastChildOf($parentNode);
}
/**
* Insert the current node to the left of (before) a sibling node
*
* WARNING: If it's an existing node it will be COPIED, not moved.
*
* @param FOFTableNested $siblingNode We will be inserted before this node
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function insertLeftOf(FOFTableNested &$siblingNode)
{
if($siblingNode->lft >= $siblingNode->rgt)
{
throw new RuntimeException('Invalid position values for the sibling node');
}
// Get a reference to the database
$db = $this->getDbo();
// Get the field names
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$fldLft = $db->qn($this->getColumnAlias('lft'));
// Nullify the PK, so a new record will be created
$pk = $this->getKeyName();
$this->$pk = null;
// Get the value of the parent node's rgt
$myLeft = $siblingNode->lft;
// Update my lft/rgt values
$this->lft = $myLeft;
$this->rgt = $myLeft + 1;
// Update sibling's lft/rgt values
$siblingNode->lft += 2;
$siblingNode->rgt += 2;
$db->transactionStart();
try
{
$db->setQuery(
$db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldLft . ' = ' . $fldLft . '+2')
->where($fldLft . ' >= ' . $db->q($myLeft))
)->execute();
$db->setQuery(
$db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldRgt . ' = ' . $fldRgt . '+2')
->where($fldRgt . ' > ' . $db->q($myLeft))
)->execute();
$this->store();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
return $this;
}
/**
* Insert the current node to the right of (after) a sibling node
*
* WARNING: If it's an existing node it will be COPIED, not moved.
*
* @param FOFTableNested $siblingNode We will be inserted after this node
*
* @return $this for chaining
* @throws Exception
* @throws RuntimeException
*/
public function insertRightOf(FOFTableNested &$siblingNode)
{
if($siblingNode->lft >= $siblingNode->rgt)
{
throw new RuntimeException('Invalid position values for the sibling node');
}
// Get a reference to the database
$db = $this->getDbo();
// Get the field names
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$fldLft = $db->qn($this->getColumnAlias('lft'));
// Nullify the PK, so a new record will be created
$pk = $this->getKeyName();
$this->$pk = null;
// Get the value of the parent node's lft
$myRight = $siblingNode->rgt;
// Update my lft/rgt values
$this->lft = $myRight + 1;
$this->rgt = $myRight + 2;
$db->transactionStart();
try
{
$db->setQuery(
$db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldRgt . ' = ' . $fldRgt . '+2')
->where($fldRgt . ' > ' . $db->q($myRight))
)->execute();
$db->setQuery(
$db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($fldLft . ' = ' . $fldLft . '+2')
->where($fldLft . ' > ' . $db->q($myRight))
)->execute();
$this->store();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
return $this;
}
/**
* Alias for insertRightOf
*
* @codeCoverageIgnore
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*/
public function insertAsSiblingOf(FOFTableNested &$siblingNode)
{
return $this->insertRightOf($siblingNode);
}
/**
* Move the current node (and its subtree) one position to the left in the tree, i.e. before its left-hand sibling
*
* @throws RuntimeException
*
* @return $this
*/
public function moveLeft()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
// If it is a root node we will not move the node (roots don't participate in tree ordering)
if ($this->isRoot())
{
return $this;
}
// Are we already the leftmost node?
$parentNode = $this->getParent();
if ($parentNode->lft == ($this->lft - 1))
{
return $this;
}
// Get the sibling to the left
$db = $this->getDbo();
$table = $this->getClone();
$table->reset();
$leftSibling = $table->whereRaw($db->qn($this->getColumnAlias('rgt')) . ' = ' . $db->q($this->lft - 1))
->get(0, 1)->current();
// Move the node
if (is_object($leftSibling) && ($leftSibling instanceof FOFTableNested))
{
return $this->moveToLeftOf($leftSibling);
}
return false;
}
/**
* Move the current node (and its subtree) one position to the right in the tree, i.e. after its right-hand sibling
*
* @throws RuntimeException
*
* @return $this
*/
public function moveRight()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
// If it is a root node we will not move the node (roots don't participate in tree ordering)
if ($this->isRoot())
{
return $this;
}
// Are we already the rightmost node?
$parentNode = $this->getParent();
if ($parentNode->rgt == ($this->rgt + 1))
{
return $this;
}
// Get the sibling to the right
$db = $this->getDbo();
$table = $this->getClone();
$table->reset();
$rightSibling = $table->whereRaw($db->qn($this->getColumnAlias('lft')) . ' = ' . $db->q($this->rgt + 1))
->get(0, 1)->current();
// Move the node
if (is_object($rightSibling) && ($rightSibling instanceof FOFTableNested))
{
return $this->moveToRightOf($rightSibling);
}
return false;
}
/**
* Moves the current node (and its subtree) to the left of another node. The other node can be in a different
* position in the tree or even under a different root.
*
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function moveToLeftOf(FOFTableNested $siblingNode)
{
// Sanity checks on current and sibling node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($siblingNode->lft >= $siblingNode->rgt)
{
throw new RuntimeException('Invalid position values for the sibling node');
}
$db = $this->getDbo();
$left = $db->qn($this->getColumnAlias('lft'));
$right = $db->qn($this->getColumnAlias('rgt'));
// Get node metrics
$myLeft = $this->lft;
$myRight = $this->rgt;
$myWidth = $myRight - $myLeft + 1;
// Get sibling metrics
$sibLeft = $siblingNode->lft;
// Start the transaction
$db->transactionStart();
try
{
// Temporary remove subtree being moved
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set("$left = " . $db->q(0) . " - $left")
->set("$right = " . $db->q(0) . " - $right")
->where($left . ' >= ' . $db->q($myLeft))
->where($right . ' <= ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Close hole left behind
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' - ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' - ' . $db->q($myWidth))
->where($right . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Make a hole for the new items
$newSibLeft = ($sibLeft > $myRight) ? $sibLeft - $myWidth : $sibLeft;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' + ' . $db->q($myWidth))
->where($right . ' >= ' . $db->q($newSibLeft));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' + ' . $db->q($myWidth))
->where($left . ' >= ' . $db->q($newSibLeft));
$db->setQuery($query)->execute();
// Move node and subnodes
$moveRight = $newSibLeft - $myLeft;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $db->q(0) . ' - ' . $left . ' + ' . $db->q($moveRight))
->set($right . ' = ' . $db->q(0) . ' - ' . $right . ' + ' . $db->q($moveRight))
->where($left . ' <= 0 - ' . $db->q($myLeft))
->where($right . ' >= 0 - ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
// Let's load the record again to fetch the new values for lft and rgt
$this->load();
return $this;
}
/**
* Moves the current node (and its subtree) to the right of another node. The other node can be in a different
* position in the tree or even under a different root.
*
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function moveToRightOf(FOFTableNested $siblingNode)
{
// Sanity checks on current and sibling node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($siblingNode->lft >= $siblingNode->rgt)
{
throw new RuntimeException('Invalid position values for the sibling node');
}
$db = $this->getDbo();
$left = $db->qn($this->getColumnAlias('lft'));
$right = $db->qn($this->getColumnAlias('rgt'));
// Get node metrics
$myLeft = $this->lft;
$myRight = $this->rgt;
$myWidth = $myRight - $myLeft + 1;
// Get parent metrics
$sibRight = $siblingNode->rgt;
// Start the transaction
$db->transactionStart();
try
{
// Temporary remove subtree being moved
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set("$left = " . $db->q(0) . " - $left")
->set("$right = " . $db->q(0) . " - $right")
->where($left . ' >= ' . $db->q($myLeft))
->where($right . ' <= ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Close hole left behind
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' - ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' - ' . $db->q($myWidth))
->where($right . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Make a hole for the new items
$newSibRight = ($sibRight > $myRight) ? $sibRight - $myWidth : $sibRight;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' + ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($newSibRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' + ' . $db->q($myWidth))
->where($right . ' > ' . $db->q($newSibRight));
$db->setQuery($query)->execute();
// Move node and subnodes
$moveRight = ($sibRight > $myRight) ? $sibRight - $myRight : $sibRight - $myRight + $myWidth;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $db->q(0) . ' - ' . $left . ' + ' . $db->q($moveRight))
->set($right . ' = ' . $db->q(0) . ' - ' . $right . ' + ' . $db->q($moveRight))
->where($left . ' <= 0 - ' . $db->q($myLeft))
->where($right . ' >= 0 - ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
// Let's load the record again to fetch the new values for lft and rgt
$this->load();
return $this;
}
/**
* Alias for moveToRightOf
*
* @codeCoverageIgnore
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*/
public function makeNextSiblingOf(FOFTableNested $siblingNode)
{
return $this->moveToRightOf($siblingNode);
}
/**
* Alias for makeNextSiblingOf
*
* @codeCoverageIgnore
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*/
public function makeSiblingOf(FOFTableNested $siblingNode)
{
return $this->makeNextSiblingOf($siblingNode);
}
/**
* Alias for moveToLeftOf
*
* @codeCoverageIgnore
* @param FOFTableNested $siblingNode
*
* @return $this for chaining
*/
public function makePreviousSiblingOf(FOFTableNested $siblingNode)
{
return $this->moveToLeftOf($siblingNode);
}
/**
* Moves a node and its subtree as a the first (leftmost) child of $parentNode
*
* @param FOFTableNested $parentNode
*
* @return $this for chaining
*
* @throws Exception
*/
public function makeFirstChildOf(FOFTableNested $parentNode)
{
// Sanity checks on current and sibling node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($parentNode->lft >= $parentNode->rgt)
{
throw new RuntimeException('Invalid position values for the parent node');
}
$db = $this->getDbo();
$left = $db->qn($this->getColumnAlias('lft'));
$right = $db->qn($this->getColumnAlias('rgt'));
// Get node metrics
$myLeft = $this->lft;
$myRight = $this->rgt;
$myWidth = $myRight - $myLeft + 1;
// Get parent metrics
$parentLeft = $parentNode->lft;
// Start the transaction
$db->transactionStart();
try
{
// Temporary remove subtree being moved
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set("$left = " . $db->q(0) . " - $left")
->set("$right = " . $db->q(0) . " - $right")
->where($left . ' >= ' . $db->q($myLeft))
->where($right . ' <= ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Close hole left behind
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' - ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' - ' . $db->q($myWidth))
->where($right . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Make a hole for the new items
$newParentLeft = ($parentLeft > $myRight) ? $parentLeft - $myWidth : $parentLeft;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' + ' . $db->q($myWidth))
->where($right . ' >= ' . $db->q($newParentLeft));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' + ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($newParentLeft));
$db->setQuery($query)->execute();
// Move node and subnodes
$moveRight = $newParentLeft - $myLeft + 1;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $db->q(0) . ' - ' . $left . ' + ' . $db->q($moveRight))
->set($right . ' = ' . $db->q(0) . ' - ' . $right . ' + ' . $db->q($moveRight))
->where($left . ' <= 0 - ' . $db->q($myLeft))
->where($right . ' >= 0 - ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
// Let's load the record again to fetch the new values for lft and rgt
$this->load();
return $this;
}
/**
* Moves a node and its subtree as a the last (rightmost) child of $parentNode
*
* @param FOFTableNested $parentNode
*
* @return $this for chaining
*
* @throws Exception
* @throws RuntimeException
*/
public function makeLastChildOf(FOFTableNested $parentNode)
{
// Sanity checks on current and sibling node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($parentNode->lft >= $parentNode->rgt)
{
throw new RuntimeException('Invalid position values for the parent node');
}
$db = $this->getDbo();
$left = $db->qn($this->getColumnAlias('lft'));
$right = $db->qn($this->getColumnAlias('rgt'));
// Get node metrics
$myLeft = $this->lft;
$myRight = $this->rgt;
$myWidth = $myRight - $myLeft + 1;
// Get parent metrics
$parentRight = $parentNode->rgt;
// Start the transaction
$db->transactionStart();
try
{
// Temporary remove subtree being moved
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set("$left = " . $db->q(0) . " - $left")
->set("$right = " . $db->q(0) . " - $right")
->where($left . ' >= ' . $db->q($myLeft))
->where($right . ' <= ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Close hole left behind
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' - ' . $db->q($myWidth))
->where($left . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' - ' . $db->q($myWidth))
->where($right . ' > ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Make a hole for the new items
$newLeft = ($parentRight > $myRight) ? $parentRight - $myWidth : $parentRight;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $left . ' + ' . $db->q($myWidth))
->where($left . ' >= ' . $db->q($newLeft));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($right . ' = ' . $right . ' + ' . $db->q($myWidth))
->where($right . ' >= ' . $db->q($newLeft));
$db->setQuery($query)->execute();
// Move node and subnodes
$moveRight = ($parentRight > $myRight) ? $parentRight - $myRight - 1 : $parentRight - $myRight - 1 + $myWidth;
$query = $db->getQuery(true)
->update($db->qn($this->getTableName()))
->set($left . ' = ' . $db->q(0) . ' - ' . $left . ' + ' . $db->q($moveRight))
->set($right . ' = ' . $db->q(0) . ' - ' . $right . ' + ' . $db->q($moveRight))
->where($left . ' <= 0 - ' . $db->q($myLeft))
->where($right . ' >= 0 - ' . $db->q($myRight));
$db->setQuery($query)->execute();
// Commit the transaction
$db->transactionCommit();
}
catch (\Exception $e)
{
$db->transactionRollback();
throw $e;
}
// Let's load the record again to fetch the new values for lft and rgt
$this->load();
return $this;
}
/**
* Alias for makeLastChildOf
*
* @codeCoverageIgnore
* @param FOFTableNested $parentNode
*
* @return $this for chaining
*/
public function makeChildOf(FOFTableNested $parentNode)
{
return $this->makeLastChildOf($parentNode);
}
/**
* Makes the current node a root (and moving its entire subtree along the way). This is achieved by moving the node
* to the right of its root node
*
* @return $this for chaining
*/
public function makeRoot()
{
// Make sure we are not a root
if ($this->isRoot())
{
return $this;
}
// Get a reference to my root
$myRoot = $this->getRoot();
// Double check I am not a root
if ($this->equals($myRoot))
{
return $this;
}
// Move myself to the right of my root
$this->moveToRightOf($myRoot);
$this->treeDepth = 0;
return $this;
}
/**
* Gets the level (depth) of this node in the tree. The result is cached in $this->treeDepth for faster retrieval.
*
* @throws RuntimeException
*
* @return int|mixed
*/
public function getLevel()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if (is_null($this->treeDepth))
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$query = $db->getQuery(true)
->select('(COUNT(' . $db->qn('parent') . '.' . $fldLft . ') - 1) AS ' . $db->qn('depth'))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->where($db->qn('node') . '.' . $fldLft . ' = ' . $db->q($this->lft))
->group($db->qn('node') . '.' . $fldLft)
->order($db->qn('node') . '.' . $fldLft . ' ASC');
$this->treeDepth = $db->setQuery($query, 0, 1)->loadResult();
}
return $this->treeDepth;
}
/**
* Returns the immediate parent of the current node
*
* @throws RuntimeException
*
* @return FOFTableNested
*/
public function getParent()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if ($this->isRoot())
{
return $this;
}
if (empty($this->treeParent) || !is_object($this->treeParent) || !($this->treeParent instanceof FOFTableNested))
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$query = $db->getQuery(true)
->select($db->qn('parent') . '.' . $fldLft)
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->where($db->qn('node') . '.' . $fldLft . ' > ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->where($db->qn('node') . '.' . $fldLft . ' = ' . $db->q($this->lft))
->order($db->qn('parent') . '.' . $fldLft . ' DESC');
$targetLft = $db->setQuery($query, 0, 1)->loadResult();
$table = $this->getClone();
$table->reset();
$this->treeParent = $table
->whereRaw($fldLft . ' = ' . $db->q($targetLft))
->get()->current();
}
return $this->treeParent;
}
/**
* Is this a top-level root node?
*
* @return bool
*/
public function isRoot()
{
// If lft=1 it is necessarily a root node
if ($this->lft == 1)
{
return true;
}
// Otherwise make sure its level is 0
return $this->getLevel() == 0;
}
/**
* Is this a leaf node (a node without children)?
*
* @throws RuntimeException
*
* @return bool
*/
public function isLeaf()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
return ($this->rgt - 1) == $this->lft;
}
/**
* Is this a child node (not root)?
*
* @codeCoverageIgnore
*
* @return bool
*/
public function isChild()
{
return !$this->isRoot();
}
/**
* Returns true if we are a descendant of $otherNode
*
* @param FOFTableNested $otherNode
*
* @throws RuntimeException
*
* @return bool
*/
public function isDescendantOf(FOFTableNested $otherNode)
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($otherNode->lft >= $otherNode->rgt)
{
throw new RuntimeException('Invalid position values for the other node');
}
return ($otherNode->lft < $this->lft) && ($otherNode->rgt > $this->rgt);
}
/**
* Returns true if $otherNode is ourselves or if we are a descendant of $otherNode
*
* @param FOFTableNested $otherNode
*
* @throws RuntimeException
*
* @return bool
*/
public function isSelfOrDescendantOf(FOFTableNested $otherNode)
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($otherNode->lft >= $otherNode->rgt)
{
throw new RuntimeException('Invalid position values for the other node');
}
return ($otherNode->lft <= $this->lft) && ($otherNode->rgt >= $this->rgt);
}
/**
* Returns true if we are an ancestor of $otherNode
*
* @codeCoverageIgnore
* @param FOFTableNested $otherNode
*
* @return bool
*/
public function isAncestorOf(FOFTableNested $otherNode)
{
return $otherNode->isDescendantOf($this);
}
/**
* Returns true if $otherNode is ourselves or we are an ancestor of $otherNode
*
* @codeCoverageIgnore
* @param FOFTableNested $otherNode
*
* @return bool
*/
public function isSelfOrAncestorOf(FOFTableNested $otherNode)
{
return $otherNode->isSelfOrDescendantOf($this);
}
/**
* Is $node this very node?
*
* @param FOFTableNested $node
*
* @throws RuntimeException
*
* @return bool
*/
public function equals(FOFTableNested &$node)
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
if($node->lft >= $node->rgt)
{
throw new RuntimeException('Invalid position values for the other node');
}
return (
($this->getId() == $node->getId())
&& ($this->lft == $node->lft)
&& ($this->rgt == $node->rgt)
);
}
/**
* Alias for isDescendantOf
*
* @codeCoverageIgnore
* @param FOFTableNested $otherNode
*
* @return bool
*/
public function insideSubtree(FOFTableNested $otherNode)
{
return $this->isDescendantOf($otherNode);
}
/**
* Returns true if both this node and $otherNode are root, leaf or child (same tree scope)
*
* @param FOFTableNested $otherNode
*
* @return bool
*/
public function inSameScope(FOFTableNested $otherNode)
{
if ($this->isLeaf())
{
return $otherNode->isLeaf();
}
elseif ($this->isRoot())
{
return $otherNode->isRoot();
}
elseif ($this->isChild())
{
return $otherNode->isChild();
}
else
{
return false;
}
}
/**
* get() will return all ancestor nodes and ourselves
*
* @return void
*/
protected function scopeAncestorsAndSelf()
{
$this->treeNestedGet = true;
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' >= ' . $db->qn('node') . '.' . $fldLft);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' <= ' . $db->qn('node') . '.' . $fldRgt);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' = ' . $db->q($this->lft));
}
/**
* get() will return all ancestor nodes but not ourselves
*
* @return void
*/
protected function scopeAncestors()
{
$this->treeNestedGet = true;
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' > ' . $db->qn('node') . '.' . $fldLft);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' < ' . $db->qn('node') . '.' . $fldRgt);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' = ' . $db->q($this->lft));
}
/**
* get() will return all sibling nodes and ourselves
*
* @return void
*/
protected function scopeSiblingsAndSelf()
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$parent = $this->getParent();
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' > ' . $db->q($parent->lft));
$this->whereRaw($db->qn('node') . '.' . $fldRgt . ' < ' . $db->q($parent->rgt));
}
/**
* get() will return all sibling nodes but not ourselves
*
* @codeCoverageIgnore
*
* @return void
*/
protected function scopeSiblings()
{
$this->scopeSiblingsAndSelf();
$this->scopeWithoutSelf();
}
/**
* get() will return only leaf nodes
*
* @return void
*/
protected function scopeLeaves()
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' = ' . $db->qn('node') . '.' . $fldRgt . ' - ' . $db->q(1));
}
/**
* get() will return all descendants (even subtrees of subtrees!) and ourselves
*
* @return void
*/
protected function scopeDescendantsAndSelf()
{
$this->treeNestedGet = true;
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft);
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' = ' . $db->q($this->lft));
}
/**
* get() will return all descendants (even subtrees of subtrees!) but not ourselves
*
* @return void
*/
protected function scopeDescendants()
{
$this->treeNestedGet = true;
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' > ' . $db->qn('parent') . '.' . $fldLft);
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' < ' . $db->qn('parent') . '.' . $fldRgt);
$this->whereRaw($db->qn('parent') . '.' . $fldLft . ' = ' . $db->q($this->lft));
}
/**
* get() will only return immediate descendants (first level children) of the current node
*
* @return void
*/
protected function scopeImmediateDescendants()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$subQuery = $db->getQuery(true)
->select(array(
$db->qn('node') . '.' . $fldLft,
'(COUNT(*) - 1) AS ' . $db->qn('depth')
))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->where($db->qn('node') . '.' . $fldLft . ' = ' . $db->q($this->lft))
->group($db->qn('node') . '.' . $fldLft)
->order($db->qn('node') . '.' . $fldLft . ' ASC');
$query = $db->getQuery(true)
->select(array(
$db->qn('node') . '.' . $fldLft,
'(COUNT(' . $db->qn('parent') . '.' . $fldLft . ') - (' .
$db->qn('sub_tree') . '.' . $db->qn('depth') . ' + 1)) AS ' . $db->qn('depth')
))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('sub_parent'))
->join('CROSS', '(' . $subQuery . ') AS ' . $db->qn('sub_tree'))
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('sub_parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('sub_parent') . '.' . $fldRgt)
->where($db->qn('sub_parent') . '.' . $fldLft . ' = ' . $db->qn('sub_tree') . '.' . $fldLft)
->group($db->qn('node') . '.' . $fldLft)
->having(array(
$db->qn('depth') . ' > ' . $db->q(0),
$db->qn('depth') . ' <= ' . $db->q(1),
))
->order($db->qn('node') . '.' . $fldLft . ' ASC');
$leftValues = $db->setQuery($query)->loadColumn();
if (empty($leftValues))
{
$leftValues = array(0);
}
array_walk($leftValues, function (&$item, $key) use (&$db)
{
$item = $db->q($item);
});
$this->whereRaw($db->qn('node') . '.' . $fldLft . ' IN (' . implode(',', $leftValues) . ')');
}
/**
* get() will not return the selected node if it's part of the query results
*
* @param FOFTableNested $node The node to exclude from the results
*
* @return void
*/
public function withoutNode(FOFTableNested $node)
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$this->whereRaw('NOT(' . $db->qn('node') . '.' . $fldLft . ' = ' . $db->q($node->lft) . ')');
}
/**
* get() will not return ourselves if it's part of the query results
*
* @codeCoverageIgnore
*
* @return void
*/
protected function scopeWithoutSelf()
{
$this->withoutNode($this);
}
/**
* get() will not return our root if it's part of the query results
*
* @codeCoverageIgnore
*
* @return void
*/
protected function scopeWithoutRoot()
{
$rootNode = $this->getRoot();
$this->withoutNode($rootNode);
}
/**
* Returns the root node of the tree this node belongs to
*
* @return self
*
* @throws \RuntimeException
*/
public function getRoot()
{
// Sanity checks on current node position
if($this->lft >= $this->rgt)
{
throw new RuntimeException('Invalid position values for the current node');
}
// If this is a root node return itself (there is no such thing as the root of a root node)
if ($this->isRoot())
{
return $this;
}
if (empty($this->treeRoot) || !is_object($this->treeRoot) || !($this->treeRoot instanceof FOFTableNested))
{
$this->treeRoot = null;
// First try to get the record with the minimum ID
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
$subQuery = $db->getQuery(true)
->select('MIN(' . $fldLft . ')')
->from($db->qn($this->getTableName()));
try
{
$table = $this->getClone();
$table->reset();
$root = $table
->whereRaw($fldLft . ' = (' . (string)$subQuery . ')')
->get(0, 1)->current();
if ($this->isDescendantOf($root))
{
$this->treeRoot = $root;
}
}
catch (\RuntimeException $e)
{
// If there is no root found throw an exception. Basically: your table is FUBAR.
throw new \RuntimeException("No root found for table " . $this->getTableName() . ", node lft=" . $this->lft);
}
// If the above method didn't work, get all roots and select the one with the appropriate lft/rgt values
if (is_null($this->treeRoot))
{
// Find the node with depth = 0, lft < our lft and rgt > our right. That's our root node.
$query = $db->getQuery(true)
->select(array(
$db->qn('node') . '.' . $fldLft,
'(COUNT(' . $db->qn('parent') . '.' . $fldLft . ') - 1) AS ' . $db->qn('depth')
))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->where($db->qn('node') . '.' . $fldLft . ' < ' . $db->q($this->lft))
->where($db->qn('node') . '.' . $fldRgt . ' > ' . $db->q($this->rgt))
->having($db->qn('depth') . ' = ' . $db->q(0))
->group($db->qn('node') . '.' . $fldLft);
// Get the lft value
$targetLeft = $db->setQuery($query)->loadResult();
if (empty($targetLeft))
{
// If there is no root found throw an exception. Basically: your table is FUBAR.
throw new \RuntimeException("No root found for table " . $this->getTableName() . ", node lft=" . $this->lft);
}
try
{
$table = $this->getClone();
$table->reset();
$this->treeRoot = $table
->whereRaw($fldLft . ' = ' . $db->q($targetLeft))
->get(0, 1)->current();
}
catch (\RuntimeException $e)
{
// If there is no root found throw an exception. Basically: your table is FUBAR.
throw new \RuntimeException("No root found for table " . $this->getTableName() . ", node lft=" . $this->lft);
}
}
}
return $this->treeRoot;
}
/**
* Get all ancestors to this node and the node itself. In other words it gets the full path to the node and the node
* itself.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getAncestorsAndSelf()
{
$this->scopeAncestorsAndSelf();
return $this->get();
}
/**
* Get all ancestors to this node and the node itself, but not the root node. If you want to
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getAncestorsAndSelfWithoutRoot()
{
$this->scopeAncestorsAndSelf();
$this->scopeWithoutRoot();
return $this->get();
}
/**
* Get all ancestors to this node but not the node itself. In other words it gets the path to the node, without the
* node itself.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getAncestors()
{
$this->scopeAncestorsAndSelf();
$this->scopeWithoutSelf();
return $this->get();
}
/**
* Get all ancestors to this node but not the node itself and its root.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getAncestorsWithoutRoot()
{
$this->scopeAncestors();
$this->scopeWithoutRoot();
return $this->get();
}
/**
* Get all sibling nodes, including ourselves
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getSiblingsAndSelf()
{
$this->scopeSiblingsAndSelf();
return $this->get();
}
/**
* Get all sibling nodes, except ourselves
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getSiblings()
{
$this->scopeSiblings();
return $this->get();
}
/**
* Get all leaf nodes in the tree. You may want to use the scopes to narrow down the search in a specific subtree or
* path.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getLeaves()
{
$this->scopeLeaves();
return $this->get();
}
/**
* Get all descendant (children) nodes and ourselves.
*
* Note: all descendant nodes, even descendants of our immediate descendants, will be returned.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getDescendantsAndSelf()
{
$this->scopeDescendantsAndSelf();
return $this->get();
}
/**
* Get only our descendant (children) nodes, not ourselves.
*
* Note: all descendant nodes, even descendants of our immediate descendants, will be returned.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getDescendants()
{
$this->scopeDescendants();
return $this->get();
}
/**
* Get the immediate descendants (children). Unlike getDescendants it only goes one level deep into the tree
* structure. Descendants of descendant nodes will not be returned.
*
* @codeCoverageIgnore
*
* @return FOFDatabaseIterator
*/
public function getImmediateDescendants()
{
$this->scopeImmediateDescendants();
return $this->get();
}
/**
* Returns a hashed array where each element's key is the value of the $key column (default: the ID column of the
* table) and its value is the value of the $column column (default: title). Each nesting level will have the value
* of the $column column prefixed by a number of $separator strings, as many as its nesting level (depth).
*
* This is useful for creating HTML select elements showing the hierarchy in a human readable format.
*
* @param string $column
* @param null $key
* @param string $seperator
*
* @return array
*/
public function getNestedList($column = 'title', $key = null, $seperator = ' ')
{
$db = $this->getDbo();
$fldLft = $db->qn($this->getColumnAlias('lft'));
$fldRgt = $db->qn($this->getColumnAlias('rgt'));
if (empty($key) || !$this->hasField($key))
{
$key = $this->getKeyName();
}
if (empty($column))
{
$column = 'title';
}
$fldKey = $db->qn($this->getColumnAlias($key));
$fldColumn = $db->qn($this->getColumnAlias($column));
$query = $db->getQuery(true)
->select(array(
$db->qn('node') . '.' . $fldKey,
$db->qn('node') . '.' . $fldColumn,
'(COUNT(' . $db->qn('parent') . '.' . $fldKey . ') - 1) AS ' . $db->qn('depth')
))
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'))
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'))
->where($db->qn('node') . '.' . $fldLft . ' >= ' . $db->qn('parent') . '.' . $fldLft)
->where($db->qn('node') . '.' . $fldLft . ' <= ' . $db->qn('parent') . '.' . $fldRgt)
->group($db->qn('node') . '.' . $fldLft)
->order($db->qn('node') . '.' . $fldLft . ' ASC');
$tempResults = $db->setQuery($query)->loadAssocList();
$ret = array();
if (!empty($tempResults))
{
foreach ($tempResults as $row)
{
$ret[$row[$key]] = str_repeat($seperator, $row['depth']) . $row[$column];
}
}
return $ret;
}
/**
* Locate a node from a given path, e.g. "/some/other/leaf"
*
* Notes:
* - This will only work when you have a "slug" and a "hash" field in your table.
* - If the path starts with "/" we will use the root with lft=1. Otherwise the first component of the path is
* supposed to be the slug of the root node.
* - If the root node is not found you'll get null as the return value
* - You will also get null if any component of the path is not found
*
* @param string $path The path to locate
*
* @return FOFTableNested|null The found node or null if nothing is found
*/
public function findByPath($path)
{
// @todo
}
public function isValid()
{
// @todo
}
public function rebuild()
{
// @todo
}
/**
* Resets cached values used to speed up querying the tree
*
* @return static for chaining
*/
protected function resetTreeCache()
{
$this->treeDepth = null;
$this->treeRoot = null;
$this->treeParent = null;
$this->treeNestedGet = false;
return $this;
}
/**
* Add custom, pre-compiled WHERE clauses for use in buildQuery. The raw WHERE clause you specify is added as is to
* the query generated by buildQuery. You are responsible for quoting and escaping the field names and data found
* inside the WHERE clause.
*
* @param string $rawWhereClause The raw WHERE clause to add
*
* @return $this For chaining
*/
public function whereRaw($rawWhereClause)
{
$this->whereClauses[] = $rawWhereClause;
return $this;
}
/**
* Builds the query for the get() method
*
* @return JDatabaseQuery
*/
protected function buildQuery()
{
$db = $this->getDbo();
$query = $db->getQuery(true)
->select($db->qn('node') . '.*')
->from($db->qn($this->getTableName()) . ' AS ' . $db->qn('node'));
if ($this->treeNestedGet)
{
$query
->join('CROSS', $db->qn($this->getTableName()) . ' AS ' . $db->qn('parent'));
}
// Apply custom WHERE clauses
if (count($this->whereClauses))
{
foreach ($this->whereClauses as $clause)
{
$query->where($clause);
}
}
return $query;
}
/**
* Returns a database iterator to retrieve records. Use the scope methods and the whereRaw method to define what
* exactly will be returned.
*
* @param integer $limitstart How many items to skip from the start, only when $overrideLimits = true
* @param integer $limit How many items to return, only when $overrideLimits = true
*
* @return FOFDatabaseIterator The data collection
*/
public function get($limitstart = 0, $limit = 0)
{
$limitstart = max($limitstart, 0);
$limit = max($limit, 0);
$query = $this->buildQuery();
$db = $this->getDbo();
$db->setQuery($query, $limitstart, $limit);
$cursor = $db->execute();
$dataCollection = FOFDatabaseIterator::getIterator($db->name, $cursor, null, $this->config['_table_class']);
return $dataCollection;
}
}
The same content is in 37 releases, Joomla 3.4.1-rc to 3.6.2. See them all, or every version of this file.