Nested.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Gedmo\Tree\Strategy,
  4. Doctrine\ORM\EntityManager,
  5. Gedmo\Tree\TreeListener,
  6. Doctrine\ORM\Query;
  7. /**
  8. * This strategy makes tree act like
  9. * nested set.
  10. *
  11. * This behavior can inpact the performance of your application
  12. * since nested set trees are slow on inserts and updates.
  13. *
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @package Gedmo.Tree.Strategy.ORM
  16. * @subpackage Nested
  17. * @link http://www.gediminasm.org
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. class Nested implements Strategy
  21. {
  22. /**
  23. * Previous sibling position
  24. */
  25. const PREV_SIBLING = 'prevSibling';
  26. /**
  27. * Next sibling position
  28. */
  29. const NEXT_SIBLING = 'nextSibling';
  30. /**
  31. * Last child position
  32. */
  33. const LAST_CHILD = 'lastChild';
  34. /**
  35. * First child position
  36. */
  37. const FIRST_CHILD = 'firstChild';
  38. /**
  39. * TreeListener
  40. *
  41. * @var AbstractTreeListener
  42. */
  43. protected $listener = null;
  44. /**
  45. * The max number of "right" field of the
  46. * tree in case few root nodes will be persisted
  47. * on one flush for node classes
  48. *
  49. * @var array
  50. */
  51. private $treeEdges = array();
  52. /**
  53. * List of pending Nodes, which needs to
  54. * be post processed because of having a parent Node
  55. * which requires some additional calculations
  56. *
  57. * @var array
  58. */
  59. private $pendingChildNodeInserts = array();
  60. /**
  61. * List of persisted nodes for specific
  62. * class to know when to process pending
  63. * inserts
  64. *
  65. * @var array
  66. */
  67. private $persistedNodes = array();
  68. /**
  69. * Number of updates for specific
  70. * classes to know if refresh is necessary
  71. *
  72. * @var array
  73. */
  74. private $updatesOnNodeClasses = array();
  75. /**
  76. * {@inheritdoc}
  77. */
  78. public function __construct(TreeListener $listener)
  79. {
  80. $this->listener = $listener;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function getName()
  86. {
  87. return Strategy::NESTED;
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function processScheduledUpdate($em, $node)
  93. {
  94. $meta = $em->getClassMetadata(get_class($node));
  95. $config = $this->listener->getConfiguration($em, $meta->name);
  96. $uow = $em->getUnitOfWork();
  97. $changeSet = $uow->getEntityChangeSet($node);
  98. if (isset($config['root']) && isset($changeSet[$config['root']])) {
  99. throw new \Gedmo\Exception\UnexpectedValueException("Root cannot be changed manualy, change parent instead");
  100. }
  101. if (isset($changeSet[$config['parent']])) {
  102. $this->updatesOnNodeClasses[$meta->name] = isset($this->updatesOnNodeClasses[$meta->name]) ?
  103. $this->updatesOnNodeClasses[$meta->name]+1 : 1;
  104. $this->updateNode($em, $node, $changeSet[$config['parent']][1]);
  105. }
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function processPostPersist($em, $node)
  111. {
  112. $meta = $em->getClassMetadata(get_class($node));
  113. $config = $this->listener->getConfiguration($em, $meta->name);
  114. if (isset($config['root'])) {
  115. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  116. $identifierField = $meta->getSingleIdentifierFieldName();
  117. $nodeId = $meta->getReflectionProperty($identifierField)->getValue($node);
  118. if ($parent) {
  119. $rootId = $meta->getReflectionProperty($config['root'])->getValue($parent);
  120. } else {
  121. $rootId = $nodeId;
  122. }
  123. $meta->getReflectionProperty($config['root'])->setValue($node, $rootId);
  124. $dql = "UPDATE {$meta->rootEntityName} node";
  125. $dql .= " SET node.{$config['root']} = {$rootId}";
  126. $dql .= " WHERE node.{$identifierField} = {$nodeId}";
  127. $em->createQuery($dql)->getSingleScalarResult();
  128. }
  129. unset($this->persistedNodes[spl_object_hash($node)]);
  130. if (!$this->persistedNodes && $this->pendingChildNodeInserts) {
  131. $pendingChildNodeInserts = $this->pendingChildNodeInserts;
  132. foreach ($pendingChildNodeInserts as $class => &$nodes) {
  133. while ($entity = array_shift($nodes)) {
  134. $this->insertChild($em, $entity);
  135. }
  136. }
  137. $this->pendingChildNodeInserts = array();
  138. }
  139. }
  140. /**
  141. * {@inheritdoc}
  142. */
  143. public function processScheduledDelete($em, $node)
  144. {
  145. $meta = $em->getClassMetadata(get_class($node));
  146. $config = $this->listener->getConfiguration($em, $meta->name);
  147. $uow = $em->getUnitOfWork();
  148. $leftValue = $meta->getReflectionProperty($config['left'])->getValue($node);
  149. $rightValue = $meta->getReflectionProperty($config['right'])->getValue($node);
  150. if (!$leftValue || !$rightValue) {
  151. return;
  152. }
  153. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  154. $diff = $rightValue - $leftValue + 1;
  155. if ($diff > 2) {
  156. $dql = "SELECT node FROM {$meta->rootEntityName} node";
  157. $dql .= " WHERE node.{$config['left']} BETWEEN :left AND :right";
  158. if (isset($config['root'])) {
  159. $dql .= " AND node.{$config['root']} = {$rootId}";
  160. }
  161. $q = $em->createQuery($dql);
  162. // get nodes for deletion
  163. $q->setParameter('left', $leftValue + 1);
  164. $q->setParameter('right', $rightValue - 1);
  165. $nodes = $q->getResult();
  166. foreach ((array)$nodes as $removalNode) {
  167. $uow->scheduleForDelete($removalNode);
  168. }
  169. }
  170. $this->shiftRL($em, $meta->rootEntityName, $rightValue + 1, -$diff, $rootId);
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function onFlushEnd($em)
  176. {
  177. // reset values
  178. $this->treeEdges = array();
  179. $this->updatesOnNodeClasses = array();
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function processPrePersist($em, $node)
  185. {
  186. $meta = $em->getClassMetadata(get_class($node));
  187. $config = $this->listener->getConfiguration($em, $meta->name);
  188. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  189. if ($parent === null) {
  190. $this->prepareRoot($em, $node);
  191. if (isset($config['level'])) {
  192. $meta->getReflectionProperty($config['level'])->setValue($node, 0);
  193. }
  194. } else {
  195. $meta->getReflectionProperty($config['left'])->setValue($node, 0);
  196. $meta->getReflectionProperty($config['right'])->setValue($node, 0);
  197. if (isset($config['level'])) {
  198. $meta->getReflectionProperty($config['level'])->setValue(
  199. $node,
  200. $meta->getReflectionProperty($config['level'])->getValue($parent) + 1
  201. );
  202. }
  203. $this->pendingChildNodeInserts[$meta->name][] = $node;
  204. }
  205. $this->persistedNodes[spl_object_hash($node)] = null;
  206. }
  207. /**
  208. * Insert a node which requires
  209. * parent synchronization
  210. *
  211. * @param EntityManager $em
  212. * @param object $node
  213. * @return void
  214. */
  215. public function insertChild(EntityManager $em, $node)
  216. {
  217. $meta = $em->getClassMetadata(get_class($node));
  218. $config = $this->listener->getConfiguration($em, $meta->name);
  219. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  220. $identifierField = $meta->getSingleIdentifierFieldName();
  221. $nodeId = $meta->getReflectionProperty($identifierField)->getValue($node);
  222. if (isset($this->pendingChildNodeInserts[$meta->name]) && count($this->pendingChildNodeInserts[$meta->name]) > 1) {
  223. $em->refresh($parent);
  224. }
  225. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($parent) : null;
  226. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  227. $this->shiftRL($em, $meta->rootEntityName, $parentRight, 2, $rootId);
  228. $meta->getReflectionProperty($config['left'])->setValue($node, $parentRight);
  229. $meta->getReflectionProperty($config['right'])->setValue($node, $parentRight + 1);
  230. $dql = "UPDATE {$meta->rootEntityName} node";
  231. $dql .= " SET node.{$config['left']} = " . ($parentRight) . ', ';
  232. $dql .= " node.{$config['right']} = " . ($parentRight + 1);
  233. $dql .= " WHERE node.{$identifierField} = {$nodeId}";
  234. $em->createQuery($dql)->getSingleScalarResult();
  235. }
  236. /**
  237. * Update the $node with a diferent $parent
  238. * destination
  239. *
  240. * @todo consider $position configurable through listener
  241. * @param EntityManager $em
  242. * @param object $node - target node
  243. * @param object $parent - destination node
  244. * @param string $position
  245. * @throws Gedmo\Exception\UnexpectedValueException
  246. * @return void
  247. */
  248. public function updateNode(EntityManager $em, $node, $parent, $position = 'firstChild')
  249. {
  250. $meta = $em->getClassMetadata(get_class($node));
  251. $config = $this->listener->getConfiguration($em, $meta->name);
  252. // if there is more than one update, need to refresh node
  253. if (!isset($this->updatesOnNodeClasses[$meta->name]) || $this->updatesOnNodeClasses[$meta->name] > 1) {
  254. $em->refresh($node);
  255. }
  256. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  257. $identifierField = $meta->getSingleIdentifierFieldName();
  258. $nodeId = $meta->getReflectionProperty($identifierField)->getValue($node);
  259. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  260. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  261. $level = 0;
  262. $treeSize = $right - $left + 1;
  263. $newRootId = null;
  264. if ($parent) {
  265. if (!isset($this->updatesOnNodeClasses[$meta->name]) || $this->updatesOnNodeClasses[$meta->name] > 1) {
  266. $em->refresh($parent);
  267. }
  268. $parentRootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($parent) : null;
  269. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  270. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  271. if ($rootId === $parentRootId && $parentLeft >= $left && $parentRight <= $right) {
  272. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  273. }
  274. if (isset($config['level'])) {
  275. $level = $meta->getReflectionProperty($config['level'])->getValue($parent);
  276. }
  277. switch ($position) {
  278. case self::PREV_SIBLING:
  279. $start = $parentLeft;
  280. break;
  281. case self::NEXT_SIBLING:
  282. $start = $parentRight + 1;
  283. break;
  284. case self::LAST_CHILD:
  285. $start = $parentRight;
  286. $level++;
  287. case self::FIRST_CHILD:
  288. default:
  289. $start = $parentLeft + 1;
  290. $level++;
  291. break;
  292. }
  293. $this->shiftRL($em, $meta->rootEntityName, $start, $treeSize, $parentRootId);
  294. if ($rootId === $parentRootId && $left >= $start) {
  295. $left += $treeSize;
  296. $meta->getReflectionProperty($config['left'])->setValue($node, $left);
  297. }
  298. if ($rootId === $parentRootId && $right >= $start) {
  299. $right += $treeSize;
  300. $meta->getReflectionProperty($config['right'])->setValue($node, $right);
  301. }
  302. $newRootId = $parentRootId;
  303. } elseif (!isset($config['root'])) {
  304. $start = $this->max($em, $meta->rootEntityName);
  305. } else {
  306. $start = 1;
  307. $newRootId = $nodeId;
  308. }
  309. $diff = $start - $left;
  310. $qb = $em->createQueryBuilder();
  311. $qb->update($meta->rootEntityName, 'node');
  312. if (isset($config['root'])) {
  313. $qb->set('node.' . $config['root'], $newRootId);
  314. }
  315. if (isset($config['level'])) {
  316. $qb->set('node.' . $config['level'], $level);
  317. }
  318. if ($treeSize > 2) {
  319. $levelDiff = isset($config['level']) ? $level - $meta->getReflectionProperty($config['level'])->getValue($node) : null;
  320. $this->shiftRangeRL(
  321. $em,
  322. $meta->rootEntityName,
  323. $left,
  324. $right,
  325. $diff,
  326. $rootId,
  327. $newRootId,
  328. $levelDiff
  329. );
  330. } else {
  331. $qb->set('node.' . $config['left'], $left + $diff);
  332. $qb->set('node.' . $config['right'], $right + $diff);
  333. }
  334. $qb->where("node.{$identifierField} = {$nodeId}");
  335. $qb->getQuery()->getSingleScalarResult();
  336. $this->shiftRL($em, $meta->rootEntityName, $left, -$treeSize, $rootId);
  337. }
  338. /**
  339. * Get the edge of tree
  340. *
  341. * @param EntityManager $em
  342. * @param string $class
  343. * @param integer $rootId
  344. * @return integer
  345. */
  346. public function max(EntityManager $em, $class, $rootId = 0)
  347. {
  348. $meta = $em->getClassMetadata($class);
  349. $config = $this->listener->getConfiguration($em, $meta->name);
  350. $dql = "SELECT MAX(node.{$config['right']}) FROM {$meta->rootEntityName} node";
  351. if (isset($config['root']) && $rootId) {
  352. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  353. }
  354. $query = $em->createQuery($dql);
  355. $right = $query->getSingleScalarResult();
  356. return intval($right);
  357. }
  358. /**
  359. * Shift tree left and right values by delta
  360. *
  361. * @param EntityManager $em
  362. * @param string $class
  363. * @param integer $first
  364. * @param integer $delta
  365. * @param integer $rootId
  366. * @return void
  367. */
  368. public function shiftRL(EntityManager $em, $class, $first, $delta, $rootId = null)
  369. {
  370. $meta = $em->getClassMetadata($class);
  371. $config = $this->listener->getConfiguration($em, $class);
  372. $sign = ($delta >= 0) ? ' + ' : ' - ';
  373. $delta = abs($delta);
  374. $dql = "UPDATE {$meta->rootEntityName} node";
  375. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$delta}";
  376. $dql .= " WHERE node.{$config['left']} >= {$first}";
  377. if (isset($config['root'])) {
  378. $dql .= " AND node.{$config['root']} = {$rootId}";
  379. }
  380. $q = $em->createQuery($dql);
  381. $q->getSingleScalarResult();
  382. $dql = "UPDATE {$meta->rootEntityName} node";
  383. $dql .= " SET node.{$config['right']} = node.{$config['right']} {$sign} {$delta}";
  384. $dql .= " WHERE node.{$config['right']} >= {$first}";
  385. if (isset($config['root'])) {
  386. $dql .= " AND node.{$config['root']} = {$rootId}";
  387. }
  388. $q = $em->createQuery($dql);
  389. $q->getSingleScalarResult();
  390. }
  391. /**
  392. * Shift range of right and left values on tree
  393. * depending on tree level diference also
  394. *
  395. * @param EntityManager $em
  396. * @param string $class
  397. * @param integer $first
  398. * @param integer $last
  399. * @param integer $delta
  400. * @param integer $rootId
  401. * @param integer $destRootId
  402. * @param integer $levelDelta
  403. * @return void
  404. */
  405. public function shiftRangeRL(EntityManager $em, $class, $first, $last, $delta, $rootId = null, $destRootId = null, $levelDelta = null)
  406. {
  407. $meta = $em->getClassMetadata($class);
  408. $config = $this->listener->getConfiguration($em, $class);
  409. $sign = ($delta >= 0) ? ' + ' : ' - ';
  410. $delta = abs($delta);
  411. $levelSign = ($levelDelta >= 0) ? ' + ' : ' - ';
  412. $levelDelta = abs($levelDelta);
  413. $dql = "UPDATE {$meta->rootEntityName} node";
  414. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$delta}";
  415. $dql .= ", node.{$config['right']} = node.{$config['right']} {$sign} {$delta}";
  416. if (isset($config['root'])) {
  417. $dql .= ", node.{$config['root']} = {$destRootId}";
  418. }
  419. if (isset($config['level'])) {
  420. $dql .= ", node.{$config['level']} = node.{$config['level']} {$levelSign} {$levelDelta}";
  421. }
  422. $dql .= " WHERE node.{$config['left']} >= {$first}";
  423. $dql .= " AND node.{$config['right']} <= {$last}";
  424. if (isset($config['root'])) {
  425. $dql .= " AND node.{$config['root']} = {$rootId}";
  426. }
  427. $q = $em->createQuery($dql);
  428. $q->getSingleScalarResult();
  429. }
  430. /**
  431. * If Node does not have parent, set it as root
  432. *
  433. * @param EntityManager $em
  434. * @param object $entity
  435. * @return void
  436. */
  437. private function prepareRoot(EntityManager $em, $node)
  438. {
  439. $meta = $em->getClassMetadata(get_class($node));
  440. $config = $this->listener->getConfiguration($em, $meta->name);
  441. if (isset($config['root'])) {
  442. $meta->getReflectionProperty($config['root'])->setValue($node, null);
  443. $meta->getReflectionProperty($config['left'])->setValue($node, 1);
  444. $meta->getReflectionProperty($config['right'])->setValue($node, 2);
  445. } else {
  446. $edge = isset($this->treeEdges[$meta->name]) ?
  447. $this->treeEdges[$meta->name] : $this->max($em, $meta->rootEntityName);
  448. $meta->getReflectionProperty($config['left'])->setValue($node, $edge + 1);
  449. $meta->getReflectionProperty($config['right'])->setValue($node, $edge + 2);
  450. $this->treeEdges[$meta->name] = $edge + 2;
  451. }
  452. }
  453. }