Nested.php 20 KB

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