1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171 |
- <?php
- namespace Gedmo\Tree\Entity\Repository;
- use Gedmo\Tool\Wrapper\EntityWrapper;
- use Doctrine\ORM\Query,
- Gedmo\Tree\Strategy,
- Gedmo\Tree\Strategy\ORM\Nested,
- Gedmo\Exception\InvalidArgumentException,
- Doctrine\ORM\Proxy\Proxy;
- /**
- * The NestedTreeRepository has some useful functions
- * to interact with NestedSet tree. Repository uses
- * the strategy used by listener
- *
- * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
- * @package Gedmo.Tree.Entity.Repository
- * @subpackage NestedTreeRepository
- * @link http://www.gediminasm.org
- * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
- */
- class NestedTreeRepository extends AbstractTreeRepository
- {
- /**
- * Get all root nodes query builder
- *
- * @return Doctrine\ORM\QueryBuilder
- */
- public function getRootNodesQueryBuilder()
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $qb = $this->_em->createQueryBuilder();
- return $qb
- ->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->isNull('node.'.$config['parent']))
- ->orderBy('node.' . $config['left'], 'ASC')
- ;
- }
- /**
- * Get all root nodes query
- *
- * @return Doctrine\ORM\Query
- */
- public function getRootNodesQuery()
- {
- return $this->getRootNodesQueryBuilder()->getQuery();
- }
- /**
- * Get all root nodes
- *
- * @return array
- */
- public function getRootNodes()
- {
- return $this->getRootNodesQuery()->getResult();
- }
- /**
- * Allows the following 'virtual' methods:
- * - persistAsFirstChild($node)
- * - persistAsFirstChildOf($node, $parent)
- * - persistAsLastChild($node)
- * - persistAsLastChildOf($node, $parent)
- * - persistAsNextSibling($node)
- * - persistAsNextSiblingOf($node, $sibling)
- * - persistAsPrevSibling($node)
- * - persistAsPrevSiblingOf($node, $sibling)
- * Inherited virtual methods:
- * - find*
- *
- * @see \Doctrine\ORM\EntityRepository
- * @throws InvalidArgumentException - If arguments are invalid
- * @throws BadMethodCallException - If the method called is an invalid find* or persistAs* method
- * or no find* either persistAs* method at all and therefore an invalid method call.
- * @return mixed - TreeNestedRepository if persistAs* is called
- */
- public function __call($method, $args)
- {
- if (substr($method, 0, 9) === 'persistAs') {
- if (!isset($args[0])) {
- throw new \Gedmo\Exception\InvalidArgumentException('Node to persist must be available as first argument');
- }
- $node = $args[0];
- $wrapped = new EntityWrapper($node, $this->_em);
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $position = substr($method, 9);
- if (substr($method, -2) === 'Of') {
- if (!isset($args[1])) {
- throw new \Gedmo\Exception\InvalidArgumentException('If "Of" is specified you must provide parent or sibling as the second argument');
- }
- $parentOrSibling = $args[1];
- $wrapped->setPropertyValue($config['parent'], $parentOrSibling);
- $position = substr($position, 0, -2);
- }
- $wrapped->setPropertyValue($config['left'], 0); // simulate changeset
- $oid = spl_object_hash($node);
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->setNodePosition($oid, $position)
- ;
- $this->_em->persist($node);
- return $this;
- }
- return parent::__call($method, $args);
- }
- /**
- * Get the Tree path query builder by given $node
- *
- * @param object $node
- * @throws InvalidArgumentException - if input is not valid
- * @return Doctrine\ORM\QueryBuilder
- */
- public function getPathQueryBuilder($node)
- {
- $meta = $this->getClassMetadata();
- if (!$node instanceof $meta->name) {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- $left = $wrapped->getPropertyValue($config['left']);
- $right = $wrapped->getPropertyValue($config['right']);
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->lte('node.'.$config['left'], $left))
- ->andWhere($qb->expr()->gte('node.'.$config['right'], $right))
- ->orderBy('node.' . $config['left'], 'ASC')
- ;
- if (isset($config['root'])) {
- $rootId = $wrapped->getPropertyValue($config['root']);
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- return $qb;
- }
- /**
- * Get the Tree path query by given $node
- *
- * @param object $node
- * @return Doctrine\ORM\Query
- */
- public function getPathQuery($node)
- {
- return $this->getPathQueryBuilder($node)->getQuery();
- }
- /**
- * Get the Tree path of Nodes by given $node
- *
- * @param object $node
- * @return array - list of Nodes in path
- */
- public function getPath($node)
- {
- return $this->getPathQuery($node)->getResult();
- }
- /**
- * Counts the children of given TreeNode
- *
- * @param object $node - if null counts all records in tree
- * @param boolean $direct - true to count only direct children
- * @throws InvalidArgumentException - if input is not valid
- * @return integer
- */
- public function childCount($node = null, $direct = false)
- {
- $count = 0;
- $meta = $this->getClassMetadata();
- $nodeId = $meta->getSingleIdentifierFieldName();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- if (null !== $node) {
- if ($node instanceof $meta->name) {
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- if ($direct) {
- $id = $wrapped->getIdentifier();
- $qb = $this->_em->createQueryBuilder();
- $qb->select($qb->expr()->count('node.' . $nodeId))
- ->from($config['useObjectClass'], 'node')
- ->where($id === null ?
- $qb->expr()->isNull('node.'.$config['parent']) :
- $qb->expr()->eq('node.'.$config['parent'], is_string($id) ? $qb->expr()->literal($id) : $id)
- )
- ;
- if (isset($config['root'])) {
- $rootId = $wrapped->getPropertyValue($config['root']);
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $q = $qb->getQuery();
- $count = intval($q->getSingleScalarResult());
- } else {
- $left = $wrapped->getPropertyValue($config['left']);
- $right = $wrapped->getPropertyValue($config['right']);
- if ($left && $right) {
- $count = ($right - $left - 1) / 2;
- }
- }
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- } else {
- $qb = $this->_em->createQueryBuilder();
- $qb->select($qb->expr()->count('node.' . $nodeId))
- ->from($config['useObjectClass'], 'node')
- ;
- if ($direct) {
- $qb->where($qb->expr()->isNull('node.'.$config['parent']));
- }
- $count = intval($qb->getQuery()->getSingleScalarResult());
- }
- return $count;
- }
- /**
- * Get tree children query builder followed by given $node
- *
- * @param object $node - if null, all tree nodes will be taken
- * @param boolean $direct - true to take only direct children
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @throws InvalidArgumentException - if input is not valid
- * @return Doctrine\ORM\QueryBuilder
- */
- public function childrenQueryBuilder($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ;
- if ($node !== null) {
- if ($node instanceof $meta->name) {
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- if ($direct) {
- $id = $wrapped->getIdentifier();
- $qb->where($id === null ?
- $qb->expr()->isNull('node.'.$config['parent']) :
- $qb->expr()->eq('node.'.$config['parent'], is_string($id) ? $qb->expr()->literal($id) : $id)
- );
- } else {
- $left = $wrapped->getPropertyValue($config['left']);
- $right = $wrapped->getPropertyValue($config['right']);
- if ($left && $right) {
- $qb
- ->where($qb->expr()->lt('node.' . $config['right'], $right))
- ->andWhere($qb->expr()->gt('node.' . $config['left'], $left))
- ;
- }
- }
- if (isset($config['root'])) {
- $rootId = $wrapped->getPropertyValue($config['root']);
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- } else {
- throw new \InvalidArgumentException("Node is not related to this repository");
- }
- } else {
- if ($direct) {
- $qb->where($qb->expr()->isNull('node.' . $config['parent']));
- }
- }
- if (!$sortByField) {
- $qb->orderBy('node.' . $config['left'], 'ASC');
- } elseif (is_array($sortByField)) {
- $fields = '';
- foreach ($sortByField as $field) {
- $fields .= 'node.'.$field.',';
- }
- $fields = rtrim($fields, ',');
- $qb->orderBy($fields, $direction);
- } else {
- if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
- $qb->orderBy('node.' . $sortByField, $direction);
- } else {
- throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
- }
- }
- return $qb;
- }
- /**
- * Get tree children query followed by given $node
- *
- * @param object $node - if null, all tree nodes will be taken
- * @param boolean $direct - true to take only direct children
- * @param string|array $sortByField - field names to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @return Doctrine\ORM\Query
- */
- public function childrenQuery($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
- {
- return $this->childrenQueryBuilder($node, $direct, $sortByField, $direction)->getQuery();
- }
- /**
- * Get list of children followed by given $node
- *
- * @param object $node - if null, all tree nodes will be taken
- * @param boolean $direct - true to take only direct children
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @return array - list of given $node children, null on failure
- */
- public function children($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
- {
- $q = $this->childrenQuery($node, $direct, $sortByField, $direction);
- return $q->getResult();
- }
- /**
- * Get tree leafs query builder
- *
- * @param object $root - root node in case of root tree is required
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @throws InvalidArgumentException - if input is not valid
- * @return Doctrine\ORM\QueryBuilder
- */
- public function getLeafsQueryBuilder($root = null, $sortByField = null, $direction = 'ASC')
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- if (isset($config['root']) && is_null($root)) {
- if (is_null($root)) {
- throw new InvalidArgumentException("If tree has root, getLeafs method requires any node of this tree");
- }
- }
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->eq('node.' . $config['right'], '1 + node.' . $config['left']))
- ;
- if (isset($config['root'])) {
- if ($root instanceof $meta->name) {
- $wrapped = new EntityWrapper($root, $this->_em);
- $rootId = $wrapped->getPropertyValue($config['root']);
- if (!$rootId) {
- throw new InvalidArgumentException("Root node must be managed");
- }
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- }
- if (!$sortByField) {
- $qb->orderBy('node.' . $config['left'], 'ASC');
- } else {
- if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
- $qb->orderBy('node.' . $sortByField, $direction);
- } else {
- throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
- }
- }
- return $qb;
- }
- /**
- * Get tree leafs query
- *
- * @param object $root - root node in case of root tree is required
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @return Doctrine\ORM\Query
- */
- public function getLeafsQuery($root = null, $sortByField = null, $direction = 'ASC')
- {
- return $this->getLeafsQueryBuilder($root, $sortByField, $direction)->getQuery();
- }
- /**
- * Get list of leaf nodes of the tree
- *
- * @param object $root - root node in case of root tree is required
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @return array
- */
- public function getLeafs($root = null, $sortByField = null, $direction = 'ASC')
- {
- return $this->getLeafsQuery($root, $sortByField, $direction)->getResult();
- }
- /**
- * Get the query builder for next siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
- * @return Doctrine\ORM\QueryBuilder
- */
- public function getNextSiblingsQueryBuilder($node, $includeSelf = false)
- {
- $meta = $this->getClassMetadata();
- if (!$node instanceof $meta->name) {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $parent = $wrapped->getPropertyValue($config['parent']);
- if (isset($config['root']) && !$parent) {
- throw new InvalidArgumentException("Cannot get siblings from tree root node");
- }
- $left = $wrapped->getPropertyValue($config['left']);
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($includeSelf ?
- $qb->expr()->gte('node.'.$config['left'], $left) :
- $qb->expr()->gt('node.'.$config['left'], $left)
- )
- ->orderBy("node.{$config['left']}", 'ASC')
- ;
- if ($parent) {
- $wrappedParent = new EntityWrapper($parent, $this->_em);
- $parentId = $wrappedParent->getIdentifier();
- $qb->andWhere($qb->expr()->eq('node.'.$config['parent'], is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId));
- } else {
- $qb->andWhere($qb->expr()->isNull('node.'.$config['parent']));
- }
- return $qb;
- }
- /**
- * Get the query for next siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @return Doctrine\ORM\Query
- */
- public function getNextSiblingsQuery($node, $includeSelf = false)
- {
- return $this->getNextSiblingsQueryBuilder($node, $includeSelf)->getQuery();
- }
- /**
- * Find the next siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @return array
- */
- public function getNextSiblings($node, $includeSelf = false)
- {
- return $this->getNextSiblingsQuery($node, $includeSelf)->getResult();
- }
- /**
- * Get query builder for previous siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
- * @return Doctrine\ORM\QueryBuilder
- */
- public function getPrevSiblingsQueryBuilder($node, $includeSelf = false)
- {
- $meta = $this->getClassMetadata();
- if (!$node instanceof $meta->name) {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $parent = $wrapped->getPropertyValue($config['parent']);
- if (isset($config['root']) && !$parent) {
- throw new InvalidArgumentException("Cannot get siblings from tree root node");
- }
- $left = $wrapped->getPropertyValue($config['left']);
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($includeSelf ?
- $qb->expr()->lte('node.'.$config['left'], $left) :
- $qb->expr()->lt('node.'.$config['left'], $left)
- )
- ->orderBy("node.{$config['left']}", 'ASC')
- ;
- if ($parent) {
- $wrappedParent = new EntityWrapper($parent, $this->_em);
- $parentId = $wrappedParent->getIdentifier();
- $qb->andWhere($qb->expr()->eq('node.'.$config['parent'], is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId));
- } else {
- $qb->andWhere($qb->expr()->isNull('node.'.$config['parent']));
- }
- return $qb;
- }
- /**
- * Get query for previous siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
- * @return Doctrine\ORM\Query
- */
- public function getPrevSiblingsQuery($node, $includeSelf = false)
- {
- return $this->getPrevSiblingsQueryBuilder($node, $includeSelf)->getQuery();
- }
- /**
- * Find the previous siblings of the given $node
- *
- * @param object $node
- * @param bool $includeSelf - include the node itself
- * @return array
- */
- public function getPrevSiblings($node, $includeSelf = false)
- {
- return $this->getPrevSiblingsQuery($node, $includeSelf)->getResult();
- }
- /**
- * Move the node down in the same level
- *
- * @param object $node
- * @param mixed $number
- * integer - number of positions to shift
- * boolean - if "true" - shift till last position
- * @throws RuntimeException - if something fails in transaction
- * @return boolean - true if shifted
- */
- public function moveDown($node, $number = 1)
- {
- $result = false;
- $meta = $this->getClassMetadata();
- if ($node instanceof $meta->name) {
- $nextSiblings = $this->getNextSiblings($node);
- if ($numSiblings = count($nextSiblings)) {
- $result = true;
- if ($number === true) {
- $number = $numSiblings;
- } elseif ($number > $numSiblings) {
- $number = $numSiblings;
- }
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->updateNode($this->_em, $node, $nextSiblings[$number - 1], Nested::NEXT_SIBLING);
- }
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- return $result;
- }
- /**
- * Move the node up in the same level
- *
- * @param object $node
- * @param mixed $number
- * integer - number of positions to shift
- * boolean - true shift till first position
- * @throws RuntimeException - if something fails in transaction
- * @return boolean - true if shifted
- */
- public function moveUp($node, $number = 1)
- {
- $result = false;
- $meta = $this->getClassMetadata();
- if ($node instanceof $meta->name) {
- $prevSiblings = array_reverse($this->getPrevSiblings($node));
- if ($numSiblings = count($prevSiblings)) {
- $result = true;
- if ($number === true) {
- $number = $numSiblings;
- } elseif ($number > $numSiblings) {
- $number = $numSiblings;
- }
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->updateNode($this->_em, $node, $prevSiblings[$number - 1], Nested::PREV_SIBLING);
- }
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- return $result;
- }
- /**
- * UNSAFE: be sure to backup before runing this method when necessary
- *
- * Removes given $node from the tree and reparents its descendants
- *
- * @param object $node
- * @throws RuntimeException - if something fails in transaction
- * @return void
- */
- public function removeFromTree($node)
- {
- $meta = $this->getClassMetadata();
- if ($node instanceof $meta->name) {
- $wrapped = new EntityWrapper($node, $this->_em);
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $right = $wrapped->getPropertyValue($config['right']);
- $left = $wrapped->getPropertyValue($config['left']);
- $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
- if ($right == $left + 1) {
- $this->removeSingle($wrapped);
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
- return; // node was a leaf
- }
- // process updates in transaction
- $this->_em->getConnection()->beginTransaction();
- try {
- $parent = $wrapped->getPropertyValue($config['parent']);
- $parentId = null;
- if ($parent) {
- $wrappedParrent = new EntityWrapper($parent, $this->_em);
- $parentId = $wrappedParrent->getIdentifier();
- }
- $pk = $meta->getSingleIdentifierFieldName();
- $nodeId = $wrapped->getIdentifier();
- $shift = -1;
- // in case if root node is removed, childs become roots
- if (isset($config['root']) && !$parent) {
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node.'.$pk, 'node.'.$config['left'], 'node.'.$config['right'])
- ->from($config['useObjectClass'], 'node')
- ->where($nodeId === null ?
- $qb->expr()->isNull('node.'.$config['parent']) :
- $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
- )
- ;
- $nodes = $qb->getQuery()->getArrayResult();
- foreach ($nodes as $newRoot) {
- $left = $newRoot[$config['left']];
- $right = $newRoot[$config['right']];
- $rootId = $newRoot[$pk];
- $shift = -($left - 1);
- $qb = $this->_em->createQueryBuilder();
- $qb->update($config['useObjectClass'], 'node')
- ->set('node.'.$config['root'], $rootId === null ?
- 'NULL' :
- (is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- )
- ->where($qb->expr()->eq('node.'.$config['root'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId))
- ->andWhere($qb->expr()->gte('node.'.$config['left'], $left))
- ->andWhere($qb->expr()->lte('node.'.$config['right'], $right))
- ;
- $qb->getQuery()->getSingleScalarResult();
- $qb = $this->_em->createQueryBuilder();
- $qb->update($config['useObjectClass'], 'node')
- ->set('node.'.$config['parent'], $parentId === null ?
- 'NULL' :
- (is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId)
- )
- ->where($nodeId === null ?
- $qb->expr()->isNull('node.'.$config['parent']) :
- $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
- )
- ->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- )
- ;
- $qb->getQuery()->getSingleScalarResult();
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
- }
- } else {
- $qb = $this->_em->createQueryBuilder();
- $qb->update($config['useObjectClass'], 'node')
- ->set('node.'.$config['parent'], null === $parentId ?
- 'NULL' :
- (is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId)
- )
- ->where($nodeId === null ?
- $qb->expr()->isNull('node.'.$config['parent']) :
- $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
- )
- ;
- if (isset($config['root'])) {
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $qb->getQuery()->getSingleScalarResult();
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
- $this->listener
- ->getStrategy($this->_em, $meta->name)
- ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
- }
- $this->removeSingle($wrapped);
- $this->_em->getConnection()->commit();
- } catch (\Exception $e) {
- $this->_em->close();
- $this->_em->getConnection()->rollback();
- die($e->getMessage());
- throw new \Gedmo\Exception\RuntimeException('Transaction failed', null, $e);
- }
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- }
- /**
- * Reorders the sibling nodes and child nodes by given $node,
- * according to the $sortByField and $direction specified
- *
- * @param object $node - from which node to start reordering the tree
- * @param string $sortByField - field name to sort by
- * @param string $direction - sort direction : "ASC" or "DESC"
- * @param boolean $verify - true to verify tree first
- * @return void
- */
- public function reorder($node, $sortByField = null, $direction = 'ASC', $verify = true)
- {
- $meta = $this->getClassMetadata();
- if ($node instanceof $meta->name) {
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- if ($verify && is_array($this->verify())) {
- return false;
- }
- $nodes = $this->children($node, true, $sortByField, $direction);
- foreach ($nodes as $node) {
- $wrapped = new EntityWrapper($node, $this->_em);
- $right = $wrapped->getPropertyValue($config['right']);
- $left = $wrapped->getPropertyValue($config['left']);
- $this->moveDown($node, true);
- if ($left != ($right - 1)) {
- $this->reorder($node, $sortByField, $direction, false);
- }
- }
- } else {
- throw new InvalidArgumentException("Node is not related to this repository");
- }
- }
- /**
- * Verifies that current tree is valid.
- * If any error is detected it will return an array
- * with a list of errors found on tree
- *
- * @return mixed
- * boolean - true on success
- * array - error list on failure
- */
- public function verify()
- {
- if (!$this->childCount()) {
- return true; // tree is empty
- }
- $errors = array();
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- if (isset($config['root'])) {
- $trees = $this->getRootNodes();
- foreach ($trees as $tree) {
- $this->verifyTree($errors, $tree);
- }
- } else {
- $this->verifyTree($errors);
- }
- return $errors ?: true;
- }
- /**
- * Tries to recover the tree
- *
- * @todo implement
- * @throws RuntimeException - if something fails in transaction
- * @return void
- */
- public function recover()
- {
- if ($this->verify() === true) {
- return;
- }
- // not yet implemented
- }
- /**
- * Retrieves the nested array or the decorated output.
- * Uses @options to handle decorations
- *
- * @throws \Gedmo\Exception\InvalidArgumentException
- * @param object $node - from which node to start reordering the tree
- * @param boolean $direct - true to take only direct children
- * @param array $options :
- * decorate: boolean (false) - retrieves tree as UL->LI tree
- * nodeDecorator: Closure (null) - uses $node as argument and returns decorated item as string
- * rootOpen: string || Closure ('<ul>') - branch start, closure will be given $children as a parameter
- * rootClose: string ('</ul>') - branch close
- * childStart: string || Closure ('<li>') - start of node, closure will be given $node as a parameter
- * childClose: string ('</li>') - close of node
- *
- * @return array|string
- */
- public function childrenHierarchy($node = null, $direct = false, array $options = array())
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- if ($node !== null) {
- if ($node instanceof $meta->name) {
- $wrapped = new EntityWrapper($node, $this->_em);
- if (!$wrapped->hasValidIdentifier()) {
- throw new InvalidArgumentException("Node is not managed by UnitOfWork");
- }
- }
- }
- // Gets the array of $node results.
- // It must be order by 'root' and 'left' field
- $nodes = $this->childrenQuery(
- $node,
- $direct,
- isset($config['root']) ? array($config['root'], $config['left']) : $config['left'],
- 'ASC'
- )->getArrayResult();
- return $this->buildTree($nodes, $options);
- }
- /**
- * {@inheritdoc}
- */
- protected function validate()
- {
- return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
- }
- /**
- * Collect errors on given tree if
- * where are any
- *
- * @param array $errors
- * @param object $root
- * @return void
- */
- private function verifyTree(&$errors, $root = null)
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $identifier = $meta->getSingleIdentifierFieldName();
- $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
- $qb = $this->_em->createQueryBuilder();
- $qb->select($qb->expr()->min('node.'.$config['left']))
- ->from($config['useObjectClass'], 'node')
- ;
- if (isset($config['root'])) {
- $qb->where($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $min = intval($qb->getQuery()->getSingleScalarResult());
- $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
- // check duplicate right and left values
- for ($i = $min; $i <= $edge; $i++) {
- $qb = $this->_em->createQueryBuilder();
- $qb->select($qb->expr()->count('node.'.$identifier))
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->orX(
- $qb->expr()->eq('node.'.$config['left'], $i),
- $qb->expr()->eq('node.'.$config['right'], $i)
- ))
- ;
- if (isset($config['root'])) {
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $count = intval($qb->getQuery()->getSingleScalarResult());
- if ($count !== 1) {
- if ($count === 0) {
- $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
- } else {
- $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
- }
- }
- }
- // check for missing parents
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->leftJoin('node.'.$config['parent'], 'parent')
- ->where($qb->expr()->isNotNull('node.'.$config['parent']))
- ->andWhere($qb->expr()->isNull('parent.'.$identifier))
- ;
- if (isset($config['root'])) {
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $nodes = $qb->getQuery()->getArrayResult();
- if (count($nodes)) {
- foreach ($nodes as $node) {
- $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
- }
- return; // loading broken relation can cause infinite loop
- }
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->lt('node.'.$config['right'], 'node.'.$config['left']))
- ;
- if (isset($config['root'])) {
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $result = $qb->getQuery()
- ->setMaxResults(1)
- ->getResult(Query::HYDRATE_ARRAY);
- $node = count($result) ? array_shift($result) : null;
- if ($node) {
- $id = $node[$identifier];
- $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
- }
- $qb = $this->_em->createQueryBuilder();
- $qb->select('node')
- ->from($config['useObjectClass'], 'node')
- ;
- if (isset($config['root'])) {
- $qb->where($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- $nodes = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
- foreach ($nodes as $node) {
- $right = $meta->getReflectionProperty($config['right'])->getValue($node);
- $left = $meta->getReflectionProperty($config['left'])->getValue($node);
- $id = $meta->getReflectionProperty($identifier)->getValue($node);
- $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
- if (!$right || !$left) {
- $errors[] = "node [{$id}] has invalid left or right values";
- } elseif ($right == $left) {
- $errors[] = "node [{$id}] has identical left and right values";
- } elseif ($parent) {
- if ($parent instanceof Proxy && !$parent->__isInitialized__) {
- $this->_em->refresh($parent);
- }
- $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
- $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
- $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
- if ($left < $parentLeft) {
- $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
- } elseif ($right > $parentRight) {
- $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
- }
- } else {
- $qb = $this->_em->createQueryBuilder();
- $qb->select($qb->expr()->count('node.'.$identifier))
- ->from($config['useObjectClass'], 'node')
- ->where($qb->expr()->lt('node.'.$config['left'], $left))
- ->andWhere($qb->expr()->gt('node.'.$config['right'], $right))
- ;
- if (isset($config['root'])) {
- $qb->andWhere($rootId === null ?
- $qb->expr()->isNull('node.'.$config['root']) :
- $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
- );
- }
- if ($count = intval($qb->getQuery()->getSingleScalarResult())) {
- $errors[] = "node [{$id}] parent field is blank, but it has a parent";
- }
- }
- }
- }
- /**
- * Removes single node without touching children
- *
- * @internal
- * @param EntityWrapper $wrapped
- * @return void
- */
- private function removeSingle(EntityWrapper $wrapped)
- {
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $pk = $meta->getSingleIdentifierFieldName();
- $nodeId = $wrapped->getIdentifier();
- // prevent from deleting whole branch
- $qb = $this->_em->createQueryBuilder();
- $qb->update($config['useObjectClass'], 'node')
- ->set('node.'.$config['left'], 0)
- ->set('node.'.$config['right'], 0)
- ->where($nodeId === null ?
- $qb->expr()->isNull('node.'.$pk) :
- $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
- )
- ;
- $qb->getQuery()->getSingleScalarResult();
- // remove the node from database
- $qb = $this->_em->createQueryBuilder();
- $qb->delete($config['useObjectClass'], 'node')
- ->where($nodeId === null ?
- $qb->expr()->isNull('node.'.$pk) :
- $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
- )
- ;
- $qb->getQuery()->getSingleScalarResult();
- // remove from identity map
- $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
- }
- /**
- * Retrieves the nested array or the decorated output.
- * Uses @options to handle decorations
- * NOTE: @nodes should be fetched and hydrated as array
- *
- * @throws \Gedmo\Exception\InvalidArgumentException
- * @param array $nodes - list o nodes to build tree
- * @param array $options :
- * decorate: boolean (false) - retrieves tree as UL->LI tree
- * nodeDecorator: Closure (null) - uses $node as argument and returns decorated item as string
- * rootOpen: string || Closure ('<ul>') - branch start, closure will be given $children as a parameter
- * rootClose: string ('</ul>') - branch close
- * childStart: string || Closure ('<li>') - start of node, closure will be given $node as a parameter
- * childClose: string ('</li>') - close of node
- *
- * @return array|string
- */
- public function buildTree(array $nodes, array $options = array())
- {
- //process the nested tree into a nested array
- $meta = $this->getClassMetadata();
- $config = $this->listener->getConfiguration($this->_em, $meta->name);
- $nestedTree = array();
- $l = 0;
- if (count($nodes) > 0) {
- // Node Stack. Used to help building the hierarchy
- $stack = array();
- foreach ($nodes as $child) {
- $item = $child;
- $item['__children'] = array();
- // Number of stack items
- $l = count($stack);
- // Check if we're dealing with different levels
- while($l > 0 && $stack[$l - 1][$config['level']] >= $item[$config['level']]) {
- array_pop($stack);
- $l--;
- }
- // Stack is empty (we are inspecting the root)
- if ($l == 0) {
- // Assigning the root child
- $i = count($nestedTree);
- $nestedTree[$i] = $item;
- $stack[] = &$nestedTree[$i];
- } else {
- // Add child to parent
- $i = count($stack[$l - 1]['__children']);
- $stack[$l - 1]['__children'][$i] = $item;
- $stack[] = &$stack[$l - 1]['__children'][$i];
- }
- }
- }
- $default = array(
- 'decorate' => false,
- 'rootOpen' => '<ul>',
- 'rootClose' => '</ul>',
- 'childOpen' => '<li>',
- 'childClose' => '</li>',
- 'nodeDecorator' => function ($node) use ($meta) {
- // override and change it, guessing which field to use
- if ($meta->hasField('title')) {
- $field = 'title';
- } else if ($meta->hasField('name')) {
- $field = 'name';
- } else {
- throw new InvalidArgumentException("Cannot find any representation field");
- }
- return $node[$field];
- }
- );
- $options = array_merge($default, $options);
- // If you don't want any html output it will return the nested array
- if (!$options['decorate']) {
- return $nestedTree;
- } elseif (!count($nestedTree)) {
- return '';
- }
- $build = function($tree) use (&$build, &$options) {
- $output = is_string($options['rootOpen']) ? $options['rootOpen'] : $options['rootOpen']($tree);
- foreach ($tree as $node) {
- $output .= is_string($options['childOpen']) ? $options['childOpen'] : $options['childOpen']($node);
- $output .= $options['nodeDecorator']($node);
- if (count($node['__children']) > 0) {
- $output .= $build($node['__children']);
- }
- $output .= is_string($options['childClose']) ? $options['childClose'] : $options['childClose']($node);
- }
- return $output . (is_string($options['rootClose']) ? $options['rootClose'] : $options['rootClose']($tree));
- };
- return $build($nestedTree);
- }
- }
|