Nested.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Gedmo\Exception\UnexpectedValueException;
  4. use Doctrine\ORM\Proxy\Proxy;
  5. use Gedmo\Tool\Wrapper\EntityWrapper;
  6. use Gedmo\Tool\Wrapper\AbstractWrapper;
  7. use Gedmo\Tree\Strategy;
  8. use Doctrine\ORM\EntityManager;
  9. use Gedmo\Tree\TreeListener;
  10. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  11. use Doctrine\ORM\Query;
  12. /**
  13. * This strategy makes tree act like
  14. * nested set.
  15. *
  16. * This behavior can inpact 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. * @package Gedmo.Tree.Strategy.ORM
  21. * @subpackage Nested
  22. * @link http://www.gediminasm.org
  23. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  24. */
  25. class Nested implements Strategy
  26. {
  27. /**
  28. * Previous sibling position
  29. */
  30. const PREV_SIBLING = 'PrevSibling';
  31. /**
  32. * Next sibling position
  33. */
  34. const NEXT_SIBLING = 'NextSibling';
  35. /**
  36. * Last child position
  37. */
  38. const LAST_CHILD = 'LastChild';
  39. /**
  40. * First child position
  41. */
  42. const FIRST_CHILD = 'FirstChild';
  43. /**
  44. * TreeListener
  45. *
  46. * @var AbstractTreeListener
  47. */
  48. protected $listener = null;
  49. /**
  50. * The max number of "right" field of the
  51. * tree in case few root nodes will be persisted
  52. * on one flush for node classes
  53. *
  54. * @var array
  55. */
  56. private $treeEdges = array();
  57. /**
  58. * Stores a list of node position strategies
  59. * for each node by object hash
  60. *
  61. * @var array
  62. */
  63. private $nodePositions = array();
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function __construct(TreeListener $listener)
  68. {
  69. $this->listener = $listener;
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function getName()
  75. {
  76. return Strategy::NESTED;
  77. }
  78. /**
  79. * Set node position strategy
  80. *
  81. * @param string $oid
  82. * @param string $position
  83. */
  84. public function setNodePosition($oid, $position)
  85. {
  86. $valid = array(
  87. self::FIRST_CHILD,
  88. self::LAST_CHILD,
  89. self::NEXT_SIBLING,
  90. self::PREV_SIBLING
  91. );
  92. if (!in_array($position, $valid, false)) {
  93. throw new \Gedmo\Exception\InvalidArgumentException("Position: {$position} is not valid in nested set tree");
  94. }
  95. $this->nodePositions[$oid] = $position;
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public function processScheduledInsertion($em, $node)
  101. {
  102. $meta = $em->getClassMetadata(get_class($node));
  103. $config = $this->listener->getConfiguration($em, $meta->name);
  104. $meta->getReflectionProperty($config['left'])->setValue($node, 0);
  105. $meta->getReflectionProperty($config['right'])->setValue($node, 0);
  106. if (isset($config['level'])) {
  107. $meta->getReflectionProperty($config['level'])->setValue($node, 0);
  108. }
  109. if (isset($config['root'])) {
  110. $meta->getReflectionProperty($config['root'])->setValue($node, 0);
  111. }
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function processScheduledUpdate($em, $node)
  117. {
  118. $meta = $em->getClassMetadata(get_class($node));
  119. $config = $this->listener->getConfiguration($em, $meta->name);
  120. $uow = $em->getUnitOfWork();
  121. $changeSet = $uow->getEntityChangeSet($node);
  122. if (isset($config['root']) && isset($changeSet[$config['root']])) {
  123. throw new \Gedmo\Exception\UnexpectedValueException("Root cannot be changed manualy, change parent instead");
  124. }
  125. $oid = spl_object_hash($node);
  126. if (isset($changeSet[$config['left']]) && isset($this->nodePositions[$oid])) {
  127. $wrapped = AbstractWrapper::wrapp($node, $em);
  128. $parent = $wrapped->getPropertyValue($config['parent']);
  129. // revert simulated changeset
  130. $uow->clearEntityChangeSet($oid);
  131. $wrapped->setPropertyValue($config['left'], $changeSet[$config['left']][0]);
  132. $uow->setOriginalEntityProperty($oid, $config['left'], $changeSet[$config['left']][0]);
  133. // set back all other changes
  134. foreach ($changeSet as $field => $set) {
  135. if ($field !== $config['left']) {
  136. $uow->setOriginalEntityProperty($oid, $field, $set[0]);
  137. $wrapped->setPropertyValue($field, $set[1]);
  138. }
  139. }
  140. $uow->recomputeSingleEntityChangeSet($meta, $node);
  141. $this->updateNode($em, $node, $parent);
  142. } elseif (isset($changeSet[$config['parent']])) {
  143. $this->updateNode($em, $node, $changeSet[$config['parent']][1]);
  144. }
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function processPostPersist($em, $node)
  150. {
  151. $meta = $em->getClassMetadata(get_class($node));
  152. $config = $this->listener->getConfiguration($em, $meta->name);
  153. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  154. $this->updateNode($em, $node, $parent, self::LAST_CHILD);
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function processScheduledDelete($em, $node)
  160. {
  161. $meta = $em->getClassMetadata(get_class($node));
  162. $config = $this->listener->getConfiguration($em, $meta->name);
  163. $uow = $em->getUnitOfWork();
  164. $wrapped = AbstractWrapper::wrapp($node, $em);
  165. $leftValue = $wrapped->getPropertyValue($config['left']);
  166. $rightValue = $wrapped->getPropertyValue($config['right']);
  167. if (!$leftValue || !$rightValue) {
  168. return;
  169. }
  170. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  171. $diff = $rightValue - $leftValue + 1;
  172. $this->shiftRL($em, $config['useObjectClass'], $rightValue + 1, -$diff, $rootId);
  173. if ($diff > 2) {
  174. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  175. $dql .= " WHERE node.{$config['left']} BETWEEN :left AND :right";
  176. if (isset($config['root'])) {
  177. $dql .= " AND node.{$config['root']} = {$rootId}";
  178. }
  179. $q = $em->createQuery($dql);
  180. // get nodes for deletion
  181. $q->setParameter('left', $leftValue + 1);
  182. $q->setParameter('right', $rightValue - 1);
  183. $nodes = $q->getResult();
  184. foreach ((array)$nodes as $removalNode) {
  185. $uow->scheduleForDelete($removalNode);
  186. }
  187. }
  188. }
  189. /**
  190. * {@inheritdoc}
  191. */
  192. public function onFlushEnd($em)
  193. {
  194. // reset values
  195. $this->treeEdges = array();
  196. $this->updatesOnNodeClasses = array();
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function processPreRemove($em, $node)
  202. {}
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function processPrePersist($em, $node)
  207. {}
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function processMetadataLoad($em, $meta)
  212. {}
  213. /**
  214. * Update the $node with a diferent $parent
  215. * destination
  216. *
  217. * @param EntityManager $em
  218. * @param object $node - target node
  219. * @param object $parent - destination node
  220. * @param string $position
  221. * @throws Gedmo\Exception\UnexpectedValueException
  222. * @return void
  223. */
  224. public function updateNode(EntityManager $em, $node, $parent, $position = 'FirstChild')
  225. {
  226. $wrapped = AbstractWrapper::wrapp($node, $em);
  227. $meta = $wrapped->getMetadata();
  228. $config = $this->listener->getConfiguration($em, $meta->name);
  229. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  230. $identifierField = $meta->getSingleIdentifierFieldName();
  231. $nodeId = $wrapped->getIdentifier();
  232. $left = $wrapped->getPropertyValue($config['left']);
  233. $right = $wrapped->getPropertyValue($config['right']);
  234. $isNewNode = empty($left) && empty($right);
  235. if ($isNewNode) {
  236. $left = 1;
  237. $right = 2;
  238. }
  239. $oid = spl_object_hash($node);
  240. if (isset($this->nodePositions[$oid])) {
  241. $position = $this->nodePositions[$oid];
  242. }
  243. $level = 0;
  244. $treeSize = $right - $left + 1;
  245. $newRootId = null;
  246. if ($parent) {
  247. $wrappedParent = AbstractWrapper::wrapp($parent, $em);
  248. $parentRootId = isset($config['root']) ? $wrappedParent->getPropertyValue($config['root']) : null;
  249. $parentLeft = $wrappedParent->getPropertyValue($config['left']);
  250. $parentRight = $wrappedParent->getPropertyValue($config['right']);
  251. if (!$isNewNode && $rootId === $parentRootId && $parentLeft >= $left && $parentRight <= $right) {
  252. throw new UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  253. }
  254. if (isset($config['level'])) {
  255. $level = $wrappedParent->getPropertyValue($config['level']);
  256. }
  257. switch ($position) {
  258. case self::PREV_SIBLING:
  259. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  260. if (is_null($newParent) && (isset($config['root']) || $isNewNode)) {
  261. throw new UnexpectedValueException("Cannot persist sibling for a root node, tree operation is not possible");
  262. }
  263. $wrapped->setPropertyValue($config['parent'], $newParent);
  264. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  265. $start = $parentLeft;
  266. break;
  267. case self::NEXT_SIBLING:
  268. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  269. if (is_null($newParent) && (isset($config['root']) || $isNewNode)) {
  270. throw new UnexpectedValueException("Cannot persist sibling for a root node, tree operation is not possible");
  271. }
  272. $wrapped->setPropertyValue($config['parent'], $newParent);
  273. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  274. $start = $parentRight + 1;
  275. break;
  276. case self::LAST_CHILD:
  277. $start = $parentRight;
  278. $level++;
  279. break;
  280. case self::FIRST_CHILD:
  281. default:
  282. $start = $parentLeft + 1;
  283. $level++;
  284. break;
  285. }
  286. $this->shiftRL($em, $config['useObjectClass'], $start, $treeSize, $parentRootId);
  287. if (!$isNewNode && $rootId === $parentRootId && $left >= $start) {
  288. $left += $treeSize;
  289. $wrapped->setPropertyValue($config['left'], $left);
  290. }
  291. if (!$isNewNode && $rootId === $parentRootId && $right >= $start) {
  292. $right += $treeSize;
  293. $wrapped->setPropertyValue($config['right'], $right);
  294. }
  295. $newRootId = $parentRootId;
  296. } elseif (!isset($config['root'])) {
  297. $start = isset($this->treeEdges[$meta->name]) ?
  298. $this->treeEdges[$meta->name] : $this->max($em, $config['useObjectClass']);
  299. $this->treeEdges[$meta->name] = $start + 2;
  300. $start++;
  301. } else {
  302. $start = 1;
  303. $newRootId = $nodeId;
  304. }
  305. $diff = $start - $left;
  306. if (!$isNewNode) {
  307. $levelDiff = isset($config['level']) ? $level - $wrapped->getPropertyValue($config['level']) : null;
  308. $this->shiftRangeRL(
  309. $em,
  310. $config['useObjectClass'],
  311. $left,
  312. $right,
  313. $diff,
  314. $rootId,
  315. $newRootId,
  316. $levelDiff
  317. );
  318. $this->shiftRL($em, $config['useObjectClass'], $left, -$treeSize, $rootId);
  319. } else {
  320. $qb = $em->createQueryBuilder();
  321. $qb->update($config['useObjectClass'], 'node');
  322. if (isset($config['root'])) {
  323. $qb->set('node.' . $config['root'], $newRootId);
  324. $wrapped->setPropertyValue($config['root'], $newRootId);
  325. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['root'], $newRootId);
  326. }
  327. if (isset($config['level'])) {
  328. $qb->set('node.' . $config['level'], $level);
  329. $wrapped->setPropertyValue($config['level'], $level);
  330. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['level'], $level);
  331. }
  332. if (isset($newParent)) {
  333. $wrappedNewParent = AbstractWrapper::wrapp($newParent, $em);
  334. $newParentId = $wrappedNewParent->getIdentifier();
  335. $qb->set('node.' . $config['parent'], $newParentId);
  336. $wrapped->setPropertyValue($config['parent'], $newParent);
  337. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['parent'], $newParent);
  338. }
  339. $qb->set('node.' . $config['left'], $left + $diff);
  340. $qb->set('node.' . $config['right'], $right + $diff);
  341. $qb->where("node.{$identifierField} = {$nodeId}");
  342. $qb->getQuery()->getSingleScalarResult();
  343. $wrapped->setPropertyValue($config['left'], $left + $diff);
  344. $wrapped->setPropertyValue($config['right'], $right + $diff);
  345. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $diff);
  346. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $diff);
  347. }
  348. }
  349. /**
  350. * Get the edge of tree
  351. *
  352. * @param EntityManager $em
  353. * @param string $class
  354. * @param integer $rootId
  355. * @return integer
  356. */
  357. public function max(EntityManager $em, $class, $rootId = 0)
  358. {
  359. $meta = $em->getClassMetadata($class);
  360. $config = $this->listener->getConfiguration($em, $meta->name);
  361. $dql = "SELECT MAX(node.{$config['right']}) FROM {$config['useObjectClass']} node";
  362. if (isset($config['root']) && $rootId) {
  363. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  364. }
  365. $query = $em->createQuery($dql);
  366. $right = $query->getSingleScalarResult();
  367. return intval($right);
  368. }
  369. /**
  370. * Shift tree left and right values by delta
  371. *
  372. * @param EntityManager $em
  373. * @param string $class
  374. * @param integer $first
  375. * @param integer $delta
  376. * @param integer $rootId
  377. * @return void
  378. */
  379. public function shiftRL(EntityManager $em, $class, $first, $delta, $rootId = null)
  380. {
  381. $meta = $em->getClassMetadata($class);
  382. $config = $this->listener->getConfiguration($em, $class);
  383. $sign = ($delta >= 0) ? ' + ' : ' - ';
  384. $absDelta = abs($delta);
  385. $dql = "UPDATE {$meta->name} node";
  386. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$absDelta}";
  387. $dql .= " WHERE node.{$config['left']} >= {$first}";
  388. if (isset($config['root'])) {
  389. $dql .= " AND node.{$config['root']} = {$rootId}";
  390. }
  391. $q = $em->createQuery($dql);
  392. $q->getSingleScalarResult();
  393. $dql = "UPDATE {$meta->name} node";
  394. $dql .= " SET node.{$config['right']} = node.{$config['right']} {$sign} {$absDelta}";
  395. $dql .= " WHERE node.{$config['right']} >= {$first}";
  396. if (isset($config['root'])) {
  397. $dql .= " AND node.{$config['root']} = {$rootId}";
  398. }
  399. $q = $em->createQuery($dql);
  400. $q->getSingleScalarResult();
  401. // update in memory nodes increases performance, saves some IO
  402. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  403. // for inheritance mapped classes, only root is always in the identity map
  404. if ($className !== $meta->rootEntityName) {
  405. continue;
  406. }
  407. foreach ($nodes as $node) {
  408. if ($node instanceof Proxy && !$node->__isInitialized__) {
  409. continue;
  410. }
  411. $oid = spl_object_hash($node);
  412. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  413. $root = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  414. if ($root === $rootId && $left >= $first) {
  415. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  416. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  417. }
  418. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  419. if ($root === $rootId && $right >= $first) {
  420. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  421. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  422. }
  423. }
  424. }
  425. }
  426. /**
  427. * Shift range of right and left values on tree
  428. * depending on tree level diference also
  429. *
  430. * @param EntityManager $em
  431. * @param string $class
  432. * @param integer $first
  433. * @param integer $last
  434. * @param integer $delta
  435. * @param integer $rootId
  436. * @param integer $destRootId
  437. * @param integer $levelDelta
  438. * @return void
  439. */
  440. public function shiftRangeRL(EntityManager $em, $class, $first, $last, $delta, $rootId = null, $destRootId = null, $levelDelta = null)
  441. {
  442. $meta = $em->getClassMetadata($class);
  443. $config = $this->listener->getConfiguration($em, $class);
  444. $sign = ($delta >= 0) ? ' + ' : ' - ';
  445. $absDelta = abs($delta);
  446. $levelSign = ($levelDelta >= 0) ? ' + ' : ' - ';
  447. $absLevelDelta = abs($levelDelta);
  448. $dql = "UPDATE {$meta->name} node";
  449. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$absDelta}";
  450. $dql .= ", node.{$config['right']} = node.{$config['right']} {$sign} {$absDelta}";
  451. if (isset($config['root'])) {
  452. $dql .= ", node.{$config['root']} = {$destRootId}";
  453. }
  454. if (isset($config['level'])) {
  455. $dql .= ", node.{$config['level']} = node.{$config['level']} {$levelSign} {$absLevelDelta}";
  456. }
  457. $dql .= " WHERE node.{$config['left']} >= {$first}";
  458. $dql .= " AND node.{$config['right']} <= {$last}";
  459. if (isset($config['root'])) {
  460. $dql .= " AND node.{$config['root']} = {$rootId}";
  461. }
  462. $q = $em->createQuery($dql);
  463. $q->getSingleScalarResult();
  464. // update in memory nodes increases performance, saves some IO
  465. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  466. // for inheritance mapped classes, only root is always in the identity map
  467. if ($className !== $meta->rootEntityName) {
  468. continue;
  469. }
  470. foreach ($nodes as $node) {
  471. if ($node instanceof Proxy && !$node->__isInitialized__) {
  472. continue;
  473. }
  474. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  475. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  476. $root = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  477. if ($root === $rootId && $left >= $first && $right <= $last) {
  478. $oid = spl_object_hash($node);
  479. $uow = $em->getUnitOfWork();
  480. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  481. $uow->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  482. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  483. $uow->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  484. if (isset($config['root'])) {
  485. $meta->getReflectionProperty($config['root'])->setValue($node, $destRootId);
  486. $uow->setOriginalEntityProperty($oid, $config['root'], $destRootId);
  487. }
  488. if (isset($config['level'])) {
  489. $level = $meta->getReflectionProperty($config['level'])->getValue($node);
  490. $meta->getReflectionProperty($config['level'])->setValue($node, $level + $levelDelta);
  491. $uow->setOriginalEntityProperty($oid, $config['level'], $level + $levelDelta);
  492. }
  493. }
  494. }
  495. }
  496. }
  497. }