Nested.php 20 KB

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