Nested.php 20 KB

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