Nested.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function processPreRemove($em, $node)
  191. {
  192. }
  193. /**
  194. * {@inheritdoc}
  195. */
  196. public function processScheduledInsertion($em, $node)
  197. {
  198. $meta = $em->getClassMetadata(get_class($node));
  199. $config = $this->listener->getConfiguration($em, $meta->name);
  200. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  201. if ($parent === null) {
  202. $this->prepareRoot($em, $node);
  203. if (isset($config['level'])) {
  204. $meta->getReflectionProperty($config['level'])->setValue($node, 0);
  205. }
  206. } else {
  207. $meta->getReflectionProperty($config['left'])->setValue($node, 0);
  208. $meta->getReflectionProperty($config['right'])->setValue($node, 0);
  209. if (isset($config['level'])) {
  210. $meta->getReflectionProperty($config['level'])->setValue(
  211. $node,
  212. $meta->getReflectionProperty($config['level'])->getValue($parent) + 1
  213. );
  214. }
  215. $this->pendingChildNodeInserts[$meta->name][] = $node;
  216. }
  217. $this->persistedNodes[spl_object_hash($node)] = null;
  218. }
  219. /**
  220. * Insert a node which requires
  221. * parent synchronization
  222. *
  223. * @param EntityManager $em
  224. * @param object $node
  225. * @return void
  226. */
  227. public function insertChild(EntityManager $em, $node)
  228. {
  229. $meta = $em->getClassMetadata(get_class($node));
  230. $config = $this->listener->getConfiguration($em, $meta->name);
  231. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  232. $identifierField = $meta->getSingleIdentifierFieldName();
  233. $nodeId = $meta->getReflectionProperty($identifierField)->getValue($node);
  234. if (isset($this->pendingChildNodeInserts[$meta->name]) && count($this->pendingChildNodeInserts[$meta->name]) > 1) {
  235. $em->refresh($parent);
  236. }
  237. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($parent) : null;
  238. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  239. $this->shiftRL($em, $meta->rootEntityName, $parentRight, 2, $rootId);
  240. $meta->getReflectionProperty($config['left'])->setValue($node, $parentRight);
  241. $meta->getReflectionProperty($config['right'])->setValue($node, $parentRight + 1);
  242. $dql = "UPDATE {$meta->rootEntityName} node";
  243. $dql .= " SET node.{$config['left']} = " . ($parentRight) . ', ';
  244. $dql .= " node.{$config['right']} = " . ($parentRight + 1);
  245. $dql .= " WHERE node.{$identifierField} = {$nodeId}";
  246. $em->createQuery($dql)->getSingleScalarResult();
  247. }
  248. /**
  249. * Update the $node with a diferent $parent
  250. * destination
  251. *
  252. * @todo consider $position configurable through listener
  253. * @param EntityManager $em
  254. * @param object $node - target node
  255. * @param object $parent - destination node
  256. * @param string $position
  257. * @throws Gedmo\Exception\UnexpectedValueException
  258. * @return void
  259. */
  260. public function updateNode(EntityManager $em, $node, $parent, $position = 'firstChild')
  261. {
  262. $meta = $em->getClassMetadata(get_class($node));
  263. $config = $this->listener->getConfiguration($em, $meta->name);
  264. // if there is more than one update, need to refresh node
  265. if (!isset($this->updatesOnNodeClasses[$meta->name]) || $this->updatesOnNodeClasses[$meta->name] > 1) {
  266. $em->refresh($node);
  267. }
  268. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  269. $identifierField = $meta->getSingleIdentifierFieldName();
  270. $nodeId = $meta->getReflectionProperty($identifierField)->getValue($node);
  271. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  272. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  273. $level = 0;
  274. $treeSize = $right - $left + 1;
  275. $newRootId = null;
  276. if ($parent) {
  277. if (!isset($this->updatesOnNodeClasses[$meta->name]) || $this->updatesOnNodeClasses[$meta->name] > 1) {
  278. $em->refresh($parent);
  279. }
  280. $parentRootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($parent) : null;
  281. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  282. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  283. if ($rootId === $parentRootId && $parentLeft >= $left && $parentRight <= $right) {
  284. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  285. }
  286. if (isset($config['level'])) {
  287. $level = $meta->getReflectionProperty($config['level'])->getValue($parent);
  288. }
  289. switch ($position) {
  290. case self::PREV_SIBLING:
  291. $start = $parentLeft;
  292. break;
  293. case self::NEXT_SIBLING:
  294. $start = $parentRight + 1;
  295. break;
  296. case self::LAST_CHILD:
  297. $start = $parentRight;
  298. $level++;
  299. case self::FIRST_CHILD:
  300. default:
  301. $start = $parentLeft + 1;
  302. $level++;
  303. break;
  304. }
  305. $this->shiftRL($em, $meta->rootEntityName, $start, $treeSize, $parentRootId);
  306. if ($rootId === $parentRootId && $left >= $start) {
  307. $left += $treeSize;
  308. $meta->getReflectionProperty($config['left'])->setValue($node, $left);
  309. }
  310. if ($rootId === $parentRootId && $right >= $start) {
  311. $right += $treeSize;
  312. $meta->getReflectionProperty($config['right'])->setValue($node, $right);
  313. }
  314. $newRootId = $parentRootId;
  315. } elseif (!isset($config['root'])) {
  316. $start = $this->max($em, $meta->rootEntityName);
  317. } else {
  318. $start = 1;
  319. $newRootId = $nodeId;
  320. }
  321. $diff = $start - $left;
  322. $qb = $em->createQueryBuilder();
  323. $qb->update($meta->rootEntityName, 'node');
  324. if (isset($config['root'])) {
  325. $qb->set('node.' . $config['root'], $newRootId);
  326. }
  327. if (isset($config['level'])) {
  328. $qb->set('node.' . $config['level'], $level);
  329. }
  330. if ($treeSize > 2) {
  331. $levelDiff = isset($config['level']) ? $level - $meta->getReflectionProperty($config['level'])->getValue($node) : null;
  332. $this->shiftRangeRL(
  333. $em,
  334. $meta->rootEntityName,
  335. $left,
  336. $right,
  337. $diff,
  338. $rootId,
  339. $newRootId,
  340. $levelDiff
  341. );
  342. } else {
  343. $qb->set('node.' . $config['left'], $left + $diff);
  344. $qb->set('node.' . $config['right'], $right + $diff);
  345. }
  346. $qb->where("node.{$identifierField} = {$nodeId}");
  347. $qb->getQuery()->getSingleScalarResult();
  348. $this->shiftRL($em, $meta->rootEntityName, $left, -$treeSize, $rootId);
  349. }
  350. /**
  351. * Get the edge of tree
  352. *
  353. * @param EntityManager $em
  354. * @param string $class
  355. * @param integer $rootId
  356. * @return integer
  357. */
  358. public function max(EntityManager $em, $class, $rootId = 0)
  359. {
  360. $meta = $em->getClassMetadata($class);
  361. $config = $this->listener->getConfiguration($em, $meta->name);
  362. $dql = "SELECT MAX(node.{$config['right']}) FROM {$meta->rootEntityName} node";
  363. if (isset($config['root']) && $rootId) {
  364. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  365. }
  366. $query = $em->createQuery($dql);
  367. $right = $query->getSingleScalarResult();
  368. return intval($right);
  369. }
  370. /**
  371. * Shift tree left and right values by delta
  372. *
  373. * @param EntityManager $em
  374. * @param string $class
  375. * @param integer $first
  376. * @param integer $delta
  377. * @param integer $rootId
  378. * @return void
  379. */
  380. public function shiftRL(EntityManager $em, $class, $first, $delta, $rootId = null)
  381. {
  382. $meta = $em->getClassMetadata($class);
  383. $config = $this->listener->getConfiguration($em, $class);
  384. $sign = ($delta >= 0) ? ' + ' : ' - ';
  385. $delta = abs($delta);
  386. $dql = "UPDATE {$meta->rootEntityName} node";
  387. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$delta}";
  388. $dql .= " WHERE node.{$config['left']} >= {$first}";
  389. if (isset($config['root'])) {
  390. $dql .= " AND node.{$config['root']} = {$rootId}";
  391. }
  392. $q = $em->createQuery($dql);
  393. $q->getSingleScalarResult();
  394. $dql = "UPDATE {$meta->rootEntityName} node";
  395. $dql .= " SET node.{$config['right']} = node.{$config['right']} {$sign} {$delta}";
  396. $dql .= " WHERE node.{$config['right']} >= {$first}";
  397. if (isset($config['root'])) {
  398. $dql .= " AND node.{$config['root']} = {$rootId}";
  399. }
  400. $q = $em->createQuery($dql);
  401. $q->getSingleScalarResult();
  402. }
  403. /**
  404. * Shift range of right and left values on tree
  405. * depending on tree level diference also
  406. *
  407. * @param EntityManager $em
  408. * @param string $class
  409. * @param integer $first
  410. * @param integer $last
  411. * @param integer $delta
  412. * @param integer $rootId
  413. * @param integer $destRootId
  414. * @param integer $levelDelta
  415. * @return void
  416. */
  417. public function shiftRangeRL(EntityManager $em, $class, $first, $last, $delta, $rootId = null, $destRootId = null, $levelDelta = null)
  418. {
  419. $meta = $em->getClassMetadata($class);
  420. $config = $this->listener->getConfiguration($em, $class);
  421. $sign = ($delta >= 0) ? ' + ' : ' - ';
  422. $delta = abs($delta);
  423. $levelSign = ($levelDelta >= 0) ? ' + ' : ' - ';
  424. $levelDelta = abs($levelDelta);
  425. $dql = "UPDATE {$meta->rootEntityName} node";
  426. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$delta}";
  427. $dql .= ", node.{$config['right']} = node.{$config['right']} {$sign} {$delta}";
  428. if (isset($config['root'])) {
  429. $dql .= ", node.{$config['root']} = {$destRootId}";
  430. }
  431. if (isset($config['level'])) {
  432. $dql .= ", node.{$config['level']} = node.{$config['level']} {$levelSign} {$levelDelta}";
  433. }
  434. $dql .= " WHERE node.{$config['left']} >= {$first}";
  435. $dql .= " AND node.{$config['right']} <= {$last}";
  436. if (isset($config['root'])) {
  437. $dql .= " AND node.{$config['root']} = {$rootId}";
  438. }
  439. $q = $em->createQuery($dql);
  440. $q->getSingleScalarResult();
  441. }
  442. /**
  443. * If Node does not have parent, set it as root
  444. *
  445. * @param EntityManager $em
  446. * @param object $entity
  447. * @return void
  448. */
  449. private function prepareRoot(EntityManager $em, $node)
  450. {
  451. $meta = $em->getClassMetadata(get_class($node));
  452. $config = $this->listener->getConfiguration($em, $meta->name);
  453. if (isset($config['root'])) {
  454. $meta->getReflectionProperty($config['root'])->setValue($node, null);
  455. $meta->getReflectionProperty($config['left'])->setValue($node, 1);
  456. $meta->getReflectionProperty($config['right'])->setValue($node, 2);
  457. } else {
  458. $edge = isset($this->treeEdges[$meta->name]) ?
  459. $this->treeEdges[$meta->name] : $this->max($em, $meta->rootEntityName);
  460. $meta->getReflectionProperty($config['left'])->setValue($node, $edge + 1);
  461. $meta->getReflectionProperty($config['right'])->setValue($node, $edge + 2);
  462. $this->treeEdges[$meta->name] = $edge + 2;
  463. }
  464. }
  465. }