Nested.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Doctrine\Common\Collections\ArrayCollection;
  4. use Doctrine\Common\Collections\Criteria;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Doctrine\ORM\Mapping\ClassMetadata;
  7. use Gedmo\Exception\UnexpectedValueException;
  8. use Doctrine\ORM\Proxy\Proxy;
  9. use Gedmo\Tool\Wrapper\AbstractWrapper;
  10. use Gedmo\Tree\Strategy;
  11. use Gedmo\Tree\TreeListener;
  12. use Gedmo\Mapping\Event\AdapterInterface;
  13. /**
  14. * This strategy makes the tree act like a nested set.
  15. *
  16. * This behavior can impact the performance of your application
  17. * since nested set trees are slow on inserts and updates.
  18. *
  19. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. class Nested implements Strategy
  23. {
  24. /**
  25. * Previous sibling position
  26. */
  27. const PREV_SIBLING = 'PrevSibling';
  28. /**
  29. * Next sibling position
  30. */
  31. const NEXT_SIBLING = 'NextSibling';
  32. /**
  33. * Last child position
  34. */
  35. const LAST_CHILD = 'LastChild';
  36. /**
  37. * First child position
  38. */
  39. const FIRST_CHILD = 'FirstChild';
  40. /**
  41. * TreeListener
  42. *
  43. * @var TreeListener
  44. */
  45. protected $listener = null;
  46. /**
  47. * The max number of "right" field of the
  48. * tree in case few root nodes will be persisted
  49. * on one flush for node classes
  50. *
  51. * @var array
  52. */
  53. private $treeEdges = array();
  54. /**
  55. * Stores a list of node position strategies
  56. * for each node by object hash
  57. *
  58. * @var array
  59. */
  60. private $nodePositions = array();
  61. /**
  62. * Stores a list of delayed nodes for correct order of updates
  63. *
  64. * @var array
  65. */
  66. private $delayedNodes = array();
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function __construct(TreeListener $listener)
  71. {
  72. $this->listener = $listener;
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function getName()
  78. {
  79. return Strategy::NESTED;
  80. }
  81. /**
  82. * Set node position strategy
  83. *
  84. * @param string $oid
  85. * @param string $position
  86. */
  87. public function setNodePosition($oid, $position)
  88. {
  89. $valid = array(
  90. self::FIRST_CHILD,
  91. self::LAST_CHILD,
  92. self::NEXT_SIBLING,
  93. self::PREV_SIBLING,
  94. );
  95. if (!in_array($position, $valid, false)) {
  96. throw new \Gedmo\Exception\InvalidArgumentException("Position: {$position} is not valid in nested set tree");
  97. }
  98. $this->nodePositions[$oid] = $position;
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. public function processScheduledInsertion($em, $node, AdapterInterface $ea)
  104. {
  105. /** @var ClassMetadata $meta */
  106. $meta = $em->getClassMetadata(get_class($node));
  107. $config = $this->listener->getConfiguration($em, $meta->name);
  108. $meta->getReflectionProperty($config['left'])->setValue($node, 0);
  109. $meta->getReflectionProperty($config['right'])->setValue($node, 0);
  110. if (isset($config['level'])) {
  111. $meta->getReflectionProperty($config['level'])->setValue($node, 0);
  112. }
  113. if (isset($config['root']) && !$meta->hasAssociation($config['root']) && !isset($config['rootIdentifierMethod'])) {
  114. $meta->getReflectionProperty($config['root'])->setValue($node, 0);
  115. } else if (isset($config['rootIdentifierMethod']) && is_null($meta->getReflectionProperty($config['root'])->getValue($node))) {
  116. $meta->getReflectionProperty($config['root'])->setValue($node, 0);
  117. }
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function processScheduledUpdate($em, $node, AdapterInterface $ea)
  123. {
  124. $meta = $em->getClassMetadata(get_class($node));
  125. $config = $this->listener->getConfiguration($em, $meta->name);
  126. $uow = $em->getUnitOfWork();
  127. $changeSet = $uow->getEntityChangeSet($node);
  128. if (isset($config['root']) && isset($changeSet[$config['root']])) {
  129. throw new \Gedmo\Exception\UnexpectedValueException("Root cannot be changed manually, change parent instead");
  130. }
  131. $oid = spl_object_hash($node);
  132. if (isset($changeSet[$config['left']]) && isset($this->nodePositions[$oid])) {
  133. $wrapped = AbstractWrapper::wrap($node, $em);
  134. $parent = $wrapped->getPropertyValue($config['parent']);
  135. // revert simulated changeset
  136. $uow->clearEntityChangeSet($oid);
  137. $wrapped->setPropertyValue($config['left'], $changeSet[$config['left']][0]);
  138. $uow->setOriginalEntityProperty($oid, $config['left'], $changeSet[$config['left']][0]);
  139. // set back all other changes
  140. foreach ($changeSet as $field => $set) {
  141. if ($field !== $config['left']) {
  142. if (is_array($set) && array_key_exists(0, $set) && array_key_exists(1, $set)) {
  143. $uow->setOriginalEntityProperty($oid, $field, $set[0]);
  144. $wrapped->setPropertyValue($field, $set[1]);
  145. } else {
  146. $uow->setOriginalEntityProperty($oid, $field, $set);
  147. $wrapped->setPropertyValue($field, $set);
  148. }
  149. }
  150. }
  151. $uow->recomputeSingleEntityChangeSet($meta, $node);
  152. $this->updateNode($em, $node, $parent);
  153. } elseif (isset($changeSet[$config['parent']])) {
  154. $this->updateNode($em, $node, $changeSet[$config['parent']][1]);
  155. }
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function processPostPersist($em, $node, AdapterInterface $ea)
  161. {
  162. $meta = $em->getClassMetadata(get_class($node));
  163. $config = $this->listener->getConfiguration($em, $meta->name);
  164. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  165. $this->updateNode($em, $node, $parent, self::LAST_CHILD);
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function processScheduledDelete($em, $node)
  171. {
  172. $meta = $em->getClassMetadata(get_class($node));
  173. $config = $this->listener->getConfiguration($em, $meta->name);
  174. $uow = $em->getUnitOfWork();
  175. $wrapped = AbstractWrapper::wrap($node, $em);
  176. $leftValue = $wrapped->getPropertyValue($config['left']);
  177. $rightValue = $wrapped->getPropertyValue($config['right']);
  178. if (!$leftValue || !$rightValue) {
  179. return;
  180. }
  181. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  182. $diff = $rightValue - $leftValue + 1;
  183. if ($diff > 2) {
  184. $qb = $em->createQueryBuilder();
  185. $qb->select('node')
  186. ->from($config['useObjectClass'], 'node')
  187. ->where($qb->expr()->between('node.' . $config['left'], '?1', '?2'))
  188. ->setParameters(array(1 => $leftValue, 2 => $rightValue));
  189. if (isset($config['root'])) {
  190. $qb->andWhere($qb->expr()->eq('node.' . $config['root'], ':rid'));
  191. $qb->setParameter('rid', $rootId);
  192. }
  193. $q = $qb->getQuery();
  194. // get nodes for deletion
  195. $nodes = $q->getResult();
  196. foreach ((array)$nodes as $removalNode) {
  197. $uow->scheduleForDelete($removalNode);
  198. }
  199. }
  200. $this->shiftRL($em, $config['useObjectClass'], $rightValue + 1, -$diff, $rootId);
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function onFlushEnd($em, AdapterInterface $ea)
  206. {
  207. // reset values
  208. $this->treeEdges = array();
  209. }
  210. /**
  211. * {@inheritdoc}
  212. */
  213. public function processPreRemove($em, $node)
  214. {
  215. }
  216. /**
  217. * {@inheritdoc}
  218. */
  219. public function processPrePersist($em, $node)
  220. {
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function processPreUpdate($em, $node)
  226. {
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. public function processMetadataLoad($em, $meta)
  232. {
  233. }
  234. /**
  235. * {@inheritdoc}
  236. */
  237. public function processPostUpdate($em, $entity, AdapterInterface $ea)
  238. {
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function processPostRemove($em, $entity, AdapterInterface $ea)
  244. {
  245. }
  246. /**
  247. * Update the $node with a diferent $parent
  248. * destination
  249. *
  250. * @param EntityManagerInterface $em
  251. * @param object $node - target node
  252. * @param object $parent - destination node
  253. * @param string $position
  254. *
  255. * @throws \Gedmo\Exception\UnexpectedValueException
  256. */
  257. public function updateNode(EntityManagerInterface $em, $node, $parent, $position = 'FirstChild')
  258. {
  259. $wrapped = AbstractWrapper::wrap($node, $em);
  260. /** @var ClassMetadata $meta */
  261. $meta = $wrapped->getMetadata();
  262. $config = $this->listener->getConfiguration($em, $meta->name);
  263. $root = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  264. $identifierField = $meta->getSingleIdentifierFieldName();
  265. $nodeId = $wrapped->getIdentifier();
  266. $left = $wrapped->getPropertyValue($config['left']);
  267. $right = $wrapped->getPropertyValue($config['right']);
  268. $isNewNode = empty($left) && empty($right);
  269. if ($isNewNode) {
  270. $left = 1;
  271. $right = 2;
  272. }
  273. $oid = spl_object_hash($node);
  274. if (isset($this->nodePositions[$oid])) {
  275. $position = $this->nodePositions[$oid];
  276. }
  277. $level = 0;
  278. $treeSize = $right - $left + 1;
  279. $newRoot = null;
  280. if ($parent) { // || (!$parent && isset($config['rootIdentifierMethod']))
  281. $wrappedParent = AbstractWrapper::wrap($parent, $em);
  282. $parentRoot = isset($config['root']) ? $wrappedParent->getPropertyValue($config['root']) : null;
  283. $parentOid = spl_object_hash($parent);
  284. $parentLeft = $wrappedParent->getPropertyValue($config['left']);
  285. $parentRight = $wrappedParent->getPropertyValue($config['right']);
  286. if (empty($parentLeft) && empty($parentRight)) {
  287. // parent node is a new node, but wasn't processed yet (due to Doctrine commit order calculator redordering)
  288. // We delay processing of node to the moment parent node will be processed
  289. if (!isset($this->delayedNodes[$parentOid])) {
  290. $this->delayedNodes[$parentOid] = array();
  291. }
  292. $this->delayedNodes[$parentOid][] = array('node' => $node, 'position' => $position);
  293. return;
  294. }
  295. if (!$isNewNode && $root === $parentRoot && $parentLeft >= $left && $parentRight <= $right) {
  296. throw new UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  297. }
  298. if (isset($config['level'])) {
  299. $level = $wrappedParent->getPropertyValue($config['level']);
  300. }
  301. switch ($position) {
  302. case self::PREV_SIBLING:
  303. if (property_exists($node, 'sibling')) {
  304. $wrappedSibling = AbstractWrapper::wrap($node->sibling, $em);
  305. $start = $wrappedSibling->getPropertyValue($config['left']);
  306. $level++;
  307. } else {
  308. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  309. if (is_null($newParent) && ((isset($config['root']) && $config['root'] == $config['parent']) || $isNewNode)) {
  310. throw new UnexpectedValueException("Cannot persist sibling for a root node, tree operation is not possible");
  311. } else if (is_null($newParent) && (isset($config['root']) || $isNewNode)) {
  312. // root is a different column from parent (pointing to another table?), do nothing
  313. } else {
  314. $wrapped->setPropertyValue($config['parent'], $newParent);
  315. }
  316. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  317. $start = $parentLeft;
  318. }
  319. break;
  320. case self::NEXT_SIBLING:
  321. if (property_exists($node, 'sibling')) {
  322. $wrappedSibling = AbstractWrapper::wrap($node->sibling, $em);
  323. $start = $wrappedSibling->getPropertyValue($config['right']) + 1;
  324. $level++;
  325. } else {
  326. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  327. if (is_null($newParent) && ((isset($config['root']) && $config['root'] == $config['parent']) || $isNewNode)) {
  328. throw new UnexpectedValueException("Cannot persist sibling for a root node, tree operation is not possible");
  329. } else if (is_null($newParent) && (isset($config['root']) || $isNewNode)) {
  330. // root is a different column from parent (pointing to another table?), do nothing
  331. } else {
  332. $wrapped->setPropertyValue($config['parent'], $newParent);
  333. }
  334. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  335. $start = $parentRight + 1;
  336. }
  337. break;
  338. case self::LAST_CHILD:
  339. $start = $parentRight;
  340. $level++;
  341. break;
  342. case self::FIRST_CHILD:
  343. default:
  344. $start = $parentLeft + 1;
  345. $level++;
  346. break;
  347. }
  348. $this->shiftRL($em, $config['useObjectClass'], $start, $treeSize, $parentRoot);
  349. if (!$isNewNode && $root === $parentRoot && $left >= $start) {
  350. $left += $treeSize;
  351. $wrapped->setPropertyValue($config['left'], $left);
  352. }
  353. if (!$isNewNode && $root === $parentRoot && $right >= $start) {
  354. $right += $treeSize;
  355. $wrapped->setPropertyValue($config['right'], $right);
  356. }
  357. $newRoot = $parentRoot;
  358. } elseif (!isset($config['root']) ||
  359. ($meta->isSingleValuedAssociation($config['root']) && ($newRoot = $meta->getFieldValue($node, $config['root'])))) {
  360. if (!isset($this->treeEdges[$meta->name])) {
  361. $this->treeEdges[$meta->name] = $this->max($em, $config['useObjectClass'], $newRoot) + 1;
  362. }
  363. $level = 0;
  364. $parentLeft = 0;
  365. $parentRight = $this->treeEdges[$meta->name];
  366. $this->treeEdges[$meta->name] += 2;
  367. switch ($position) {
  368. case self::PREV_SIBLING:
  369. if (property_exists($node, 'sibling')) {
  370. $wrappedSibling = AbstractWrapper::wrap($node->sibling, $em);
  371. $start = $wrappedSibling->getPropertyValue($config['left']);
  372. } else {
  373. $wrapped->setPropertyValue($config['parent'], null);
  374. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  375. $start = $parentLeft + 1;
  376. }
  377. break;
  378. case self::NEXT_SIBLING:
  379. if (property_exists($node, 'sibling')) {
  380. $wrappedSibling = AbstractWrapper::wrap($node->sibling, $em);
  381. $start = $wrappedSibling->getPropertyValue($config['right']) + 1;
  382. } else {
  383. $wrapped->setPropertyValue($config['parent'], null);
  384. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  385. $start = $parentRight;
  386. }
  387. break;
  388. case self::LAST_CHILD:
  389. $start = $parentRight;
  390. break;
  391. case self::FIRST_CHILD:
  392. default:
  393. $start = $parentLeft + 1;
  394. break;
  395. }
  396. $this->shiftRL($em, $config['useObjectClass'], $start, $treeSize, null);
  397. if (!$isNewNode && $left >= $start) {
  398. $left += $treeSize;
  399. $wrapped->setPropertyValue($config['left'], $left);
  400. }
  401. if (!$isNewNode && $right >= $start) {
  402. $right += $treeSize;
  403. $wrapped->setPropertyValue($config['right'], $right);
  404. }
  405. } else {
  406. $start = 1;
  407. if (isset($config['rootIdentifierMethod'])) {
  408. $method = $config['rootIdentifierMethod'];
  409. $newRoot = $node->$method();
  410. $repo = $em->getRepository($config['useObjectClass']);
  411. $criteria = new Criteria();
  412. $criteria->andWhere(Criteria::expr()->notIn($wrapped->getMetadata()->identifier[0], [$wrapped->getIdentifier()]));
  413. $criteria->andWhere(Criteria::expr()->eq($config['root'], $node->$method()));
  414. $criteria->andWhere(Criteria::expr()->isNull($config['parent']));
  415. $criteria->andWhere(Criteria::expr()->eq($config['level'], 0));
  416. $criteria->orderBy([$config['right'] => Criteria::ASC]);
  417. $roots = $repo->matching($criteria)->toArray();
  418. $last = array_pop($roots);
  419. $start = ($last) ? $meta->getFieldValue($last, $config['right']) + 1 : 1;
  420. } else if ($meta->isSingleValuedAssociation($config['root'])) {
  421. $newRoot = $node;
  422. } else {
  423. $newRoot = $wrapped->getIdentifier();
  424. }
  425. }
  426. $diff = $start - $left;
  427. if (!$isNewNode) {
  428. $levelDiff = isset($config['level']) ? $level - $wrapped->getPropertyValue($config['level']) : null;
  429. $this->shiftRangeRL(
  430. $em,
  431. $config['useObjectClass'],
  432. $left,
  433. $right,
  434. $diff,
  435. $root,
  436. $newRoot,
  437. $levelDiff
  438. );
  439. $this->shiftRL($em, $config['useObjectClass'], $left, -$treeSize, $root);
  440. } else {
  441. $qb = $em->createQueryBuilder();
  442. $qb->update($config['useObjectClass'], 'node');
  443. if (isset($config['root'])) {
  444. $qb->set('node.' . $config['root'], ':rid');
  445. $qb->setParameter('rid', $newRoot);
  446. $wrapped->setPropertyValue($config['root'], $newRoot);
  447. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['root'], $newRoot);
  448. }
  449. if (isset($config['level'])) {
  450. $qb->set('node.' . $config['level'], $level);
  451. $wrapped->setPropertyValue($config['level'], $level);
  452. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['level'], $level);
  453. }
  454. if (isset($newParent)) {
  455. $wrappedNewParent = AbstractWrapper::wrap($newParent, $em);
  456. $newParentId = $wrappedNewParent->getIdentifier();
  457. $qb->set('node.' . $config['parent'], ':pid');
  458. $qb->setParameter('pid', $newParentId);
  459. $wrapped->setPropertyValue($config['parent'], $newParent);
  460. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['parent'], $newParent);
  461. }
  462. $qb->set('node.' . $config['left'], $left + $diff);
  463. $qb->set('node.' . $config['right'], $right + $diff);
  464. // node id cannot be null
  465. $qb->where($qb->expr()->eq('node.' . $identifierField, ':id'));
  466. $qb->setParameter('id', $nodeId);
  467. $qb->getQuery()->getSingleScalarResult();
  468. $wrapped->setPropertyValue($config['left'], $left + $diff);
  469. $wrapped->setPropertyValue($config['right'], $right + $diff);
  470. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $diff);
  471. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $diff);
  472. }
  473. if (isset($this->delayedNodes[$oid])) {
  474. foreach ($this->delayedNodes[$oid] as $nodeData) {
  475. $this->updateNode($em, $nodeData['node'], $node, $nodeData['position']);
  476. }
  477. }
  478. }
  479. /**
  480. * Get the edge of tree
  481. *
  482. * @param EntityManagerInterface $em
  483. * @param string $class
  484. * @param integer $rootId
  485. *
  486. * @return integer
  487. */
  488. public function max(EntityManagerInterface $em, $class, $rootId = 0)
  489. {
  490. $meta = $em->getClassMetadata($class);
  491. $config = $this->listener->getConfiguration($em, $meta->name);
  492. $qb = $em->createQueryBuilder();
  493. $qb->select($qb->expr()->max('node.' . $config['right']))
  494. ->from($config['useObjectClass'], 'node');
  495. if (isset($config['root']) && $rootId) {
  496. $qb->where($qb->expr()->eq('node.' . $config['root'], ':rid'));
  497. $qb->setParameter('rid', $rootId);
  498. }
  499. $query = $qb->getQuery();
  500. $right = $query->getSingleScalarResult();
  501. return intval($right);
  502. }
  503. /**
  504. * Shift tree left and right values by delta
  505. *
  506. * @param EntityManager $em
  507. * @param string $class
  508. * @param integer $first
  509. * @param integer $delta
  510. * @param EntityManagerInterface $em
  511. * @param string $class
  512. * @param integer $first
  513. * @param integer $delta
  514. * @param integer|string $root
  515. */
  516. public function shiftRL(EntityManagerInterface $em, $class, $first, $delta, $root = null)
  517. {
  518. $meta = $em->getClassMetadata($class);
  519. $config = $this->listener->getConfiguration($em, $class);
  520. $sign = ($delta >= 0) ? ' + ' : ' - ';
  521. $absDelta = abs($delta);
  522. $qb = $em->createQueryBuilder();
  523. $qb->update($config['useObjectClass'], 'node')
  524. ->set('node.' . $config['left'], "node.{$config['left']} {$sign} {$absDelta}")
  525. ->where($qb->expr()->gte('node.' . $config['left'], $first));
  526. if (isset($config['root'])) {
  527. $qb->andWhere($qb->expr()->eq('node.' . $config['root'], ':rid'));
  528. $qb->setParameter('rid', $root);
  529. }
  530. $qb->getQuery()->getSingleScalarResult();
  531. $qb = $em->createQueryBuilder();
  532. $qb->update($config['useObjectClass'], 'node')
  533. ->set('node.' . $config['right'], "node.{$config['right']} {$sign} {$absDelta}")
  534. ->where($qb->expr()->gte('node.' . $config['right'], $first));
  535. if (isset($config['root'])) {
  536. $qb->andWhere($qb->expr()->eq('node.' . $config['root'], ':rid'));
  537. $qb->setParameter('rid', $root);
  538. }
  539. $qb->getQuery()->getSingleScalarResult();
  540. // update in memory nodes increases performance, saves some IO
  541. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  542. // for inheritance mapped classes, only root is always in the identity map
  543. if ($className !== $meta->rootEntityName) {
  544. continue;
  545. }
  546. foreach ($nodes as $node) {
  547. if ($node instanceof Proxy && !$node->__isInitialized__) {
  548. continue;
  549. }
  550. $nodeMeta = $em->getClassMetadata(get_class($node));
  551. if (!array_key_exists($config['left'], $nodeMeta->getReflectionProperties())) {
  552. continue;
  553. }
  554. $oid = spl_object_hash($node);
  555. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  556. $currentRoot = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  557. if ($currentRoot === $root && $left >= $first) {
  558. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  559. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  560. }
  561. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  562. if ($currentRoot === $root && $right >= $first) {
  563. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  564. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  565. }
  566. }
  567. }
  568. }
  569. /**
  570. * Shift range of right and left values on tree
  571. * depending on tree level difference also
  572. *
  573. * @param EntityManagerInterface $em
  574. * @param string $class
  575. * @param integer $first
  576. * @param integer $last
  577. * @param integer $delta
  578. * @param integer|string $root
  579. * @param integer|string $destRoot
  580. * @param integer $levelDelta
  581. */
  582. public function shiftRangeRL(EntityManagerInterface $em, $class, $first, $last, $delta, $root = null, $destRoot = null, $levelDelta = null)
  583. {
  584. $meta = $em->getClassMetadata($class);
  585. $config = $this->listener->getConfiguration($em, $class);
  586. $sign = ($delta >= 0) ? ' + ' : ' - ';
  587. $absDelta = abs($delta);
  588. $levelSign = ($levelDelta >= 0) ? ' + ' : ' - ';
  589. $absLevelDelta = abs($levelDelta);
  590. $qb = $em->createQueryBuilder();
  591. $qb->update($config['useObjectClass'], 'node')
  592. ->set('node.' . $config['left'], "node.{$config['left']} {$sign} {$absDelta}")
  593. ->set('node.' . $config['right'], "node.{$config['right']} {$sign} {$absDelta}")
  594. ->where($qb->expr()->gte('node.' . $config['left'], $first))
  595. ->andWhere($qb->expr()->lte('node.' . $config['right'], $last));
  596. if (isset($config['root'])) {
  597. $qb->set('node.' . $config['root'], ':drid');
  598. $qb->setParameter('drid', $destRoot);
  599. $qb->andWhere($qb->expr()->eq('node.' . $config['root'], ':rid'));
  600. $qb->setParameter('rid', $root);
  601. }
  602. if (isset($config['level'])) {
  603. $qb->set('node.' . $config['level'], "node.{$config['level']} {$levelSign} {$absLevelDelta}");
  604. }
  605. $qb->getQuery()->getSingleScalarResult();
  606. // update in memory nodes increases performance, saves some IO
  607. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  608. // for inheritance mapped classes, only root is always in the identity map
  609. if ($className !== $meta->rootEntityName) {
  610. continue;
  611. }
  612. foreach ($nodes as $node) {
  613. if ($node instanceof Proxy && !$node->__isInitialized__) {
  614. continue;
  615. }
  616. $nodeMeta = $em->getClassMetadata(get_class($node));
  617. if (!array_key_exists($config['left'], $nodeMeta->getReflectionProperties())) {
  618. continue;
  619. }
  620. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  621. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  622. $currentRoot = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  623. if ($currentRoot === $root && $left >= $first && $right <= $last) {
  624. $oid = spl_object_hash($node);
  625. $uow = $em->getUnitOfWork();
  626. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  627. $uow->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  628. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  629. $uow->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  630. if (isset($config['root'])) {
  631. $meta->getReflectionProperty($config['root'])->setValue($node, $destRoot);
  632. $uow->setOriginalEntityProperty($oid, $config['root'], $destRoot);
  633. }
  634. if (isset($config['level'])) {
  635. $level = $meta->getReflectionProperty($config['level'])->getValue($node);
  636. $meta->getReflectionProperty($config['level'])->setValue($node, $level + $levelDelta);
  637. $uow->setOriginalEntityProperty($oid, $config['level'], $level + $levelDelta);
  638. }
  639. }
  640. }
  641. }
  642. }
  643. }