Nested.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. $oid = spl_object_hash($node);
  124. if (isset($changeSet[$config['left']]) && isset($this->nodePositions[$oid])) {
  125. $wrapped = AbstractWrapper::wrapp($node, $em);
  126. $parent = $wrapped->getPropertyValue($config['parent']);
  127. // revert simulated changeset
  128. $uow->clearEntityChangeSet($oid);
  129. $wrapped->setPropertyValue($config['left'], $changeSet[$config['left']][0]);
  130. $uow->setOriginalEntityProperty($oid, $config['left'], $changeSet[$config['left']][0]);
  131. // set back all other changes
  132. foreach ($changeSet as $field => $set) {
  133. if ($field !== $config['left']) {
  134. $uow->setOriginalEntityProperty($oid, $field, $set[0]);
  135. $wrapped->setPropertyValue($field, $set[1]);
  136. }
  137. }
  138. $uow->recomputeSingleEntityChangeSet($meta, $node);
  139. $this->updateNode($em, $node, $parent);
  140. } elseif (isset($changeSet[$config['parent']])) {
  141. $this->updateNode($em, $node, $changeSet[$config['parent']][1]);
  142. }
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function processPostPersist($em, $node)
  148. {
  149. $meta = $em->getClassMetadata(get_class($node));
  150. $config = $this->listener->getConfiguration($em, $meta->name);
  151. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  152. $this->updateNode($em, $node, $parent, self::LAST_CHILD);
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. public function processScheduledDelete($em, $node)
  158. {
  159. $meta = $em->getClassMetadata(get_class($node));
  160. $config = $this->listener->getConfiguration($em, $meta->name);
  161. $uow = $em->getUnitOfWork();
  162. $wrapped = AbstractWrapper::wrapp($node, $em);
  163. $leftValue = $wrapped->getPropertyValue($config['left']);
  164. $rightValue = $wrapped->getPropertyValue($config['right']);
  165. if (!$leftValue || !$rightValue) {
  166. return;
  167. }
  168. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  169. $diff = $rightValue - $leftValue + 1;
  170. if ($diff > 2) {
  171. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  172. $dql .= " WHERE node.{$config['left']} BETWEEN :left AND :right";
  173. if (isset($config['root'])) {
  174. $dql .= " AND node.{$config['root']} = {$rootId}";
  175. }
  176. $q = $em->createQuery($dql);
  177. // get nodes for deletion
  178. $q->setParameter('left', $leftValue + 1);
  179. $q->setParameter('right', $rightValue - 1);
  180. $nodes = $q->getResult();
  181. foreach ((array)$nodes as $removalNode) {
  182. $uow->scheduleForDelete($removalNode);
  183. }
  184. }
  185. $this->shiftRL($em, $config['useObjectClass'], $rightValue + 1, -$diff, $rootId);
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function onFlushEnd($em)
  191. {
  192. // reset values
  193. $this->treeEdges = array();
  194. $this->updatesOnNodeClasses = array();
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function processPreRemove($em, $node)
  200. {}
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function processPrePersist($em, $node)
  205. {}
  206. /**
  207. * {@inheritdoc}
  208. */
  209. public function processMetadataLoad($em, $meta)
  210. {}
  211. /**
  212. * Update the $node with a diferent $parent
  213. * destination
  214. *
  215. * @param EntityManager $em
  216. * @param object $node - target node
  217. * @param object $parent - destination node
  218. * @param string $position
  219. * @throws Gedmo\Exception\UnexpectedValueException
  220. * @return void
  221. */
  222. public function updateNode(EntityManager $em, $node, $parent, $position = 'FirstChild')
  223. {
  224. $wrapped = AbstractWrapper::wrapp($node, $em);
  225. $meta = $wrapped->getMetadata();
  226. $config = $this->listener->getConfiguration($em, $meta->name);
  227. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  228. $identifierField = $meta->getSingleIdentifierFieldName();
  229. $nodeId = $wrapped->getIdentifier();
  230. $left = $wrapped->getPropertyValue($config['left']);
  231. $right = $wrapped->getPropertyValue($config['right']);
  232. $isNewNode = empty($left) && empty($right);
  233. if ($isNewNode) {
  234. $left = 1;
  235. $right = 2;
  236. }
  237. $oid = spl_object_hash($node);
  238. if (isset($this->nodePositions[$oid])) {
  239. $position = $this->nodePositions[$oid];
  240. }
  241. $level = 0;
  242. $treeSize = $right - $left + 1;
  243. $newRootId = null;
  244. if ($parent) {
  245. $wrappedParent = AbstractWrapper::wrapp($parent, $em);
  246. $parentRootId = isset($config['root']) ? $wrappedParent->getPropertyValue($config['root']) : null;
  247. $parentLeft = $wrappedParent->getPropertyValue($config['left']);
  248. $parentRight = $wrappedParent->getPropertyValue($config['right']);
  249. if (!$isNewNode && $rootId === $parentRootId && $parentLeft >= $left && $parentRight <= $right) {
  250. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  251. }
  252. if (isset($config['level'])) {
  253. $level = $wrappedParent->getPropertyValue($config['level']);
  254. }
  255. switch ($position) {
  256. case self::PREV_SIBLING:
  257. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  258. $wrapped->setPropertyValue($config['parent'], $newParent);
  259. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  260. $start = $parentLeft;
  261. break;
  262. case self::NEXT_SIBLING:
  263. $newParent = $wrappedParent->getPropertyValue($config['parent']);
  264. $wrapped->setPropertyValue($config['parent'], $newParent);
  265. $em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $node);
  266. $start = $parentRight + 1;
  267. break;
  268. case self::LAST_CHILD:
  269. $start = $parentRight;
  270. $level++;
  271. break;
  272. case self::FIRST_CHILD:
  273. default:
  274. $start = $parentLeft + 1;
  275. $level++;
  276. break;
  277. }
  278. $this->shiftRL($em, $config['useObjectClass'], $start, $treeSize, $parentRootId);
  279. if (!$isNewNode && $rootId === $parentRootId && $left >= $start) {
  280. $left += $treeSize;
  281. $wrapped->setPropertyValue($config['left'], $left);
  282. }
  283. if (!$isNewNode && $rootId === $parentRootId && $right >= $start) {
  284. $right += $treeSize;
  285. $wrapped->setPropertyValue($config['right'], $right);
  286. }
  287. $newRootId = $parentRootId;
  288. } elseif (!isset($config['root'])) {
  289. $start = isset($this->treeEdges[$meta->name]) ?
  290. $this->treeEdges[$meta->name] : $this->max($em, $config['useObjectClass']);
  291. $this->treeEdges[$meta->name] = $start + 2;
  292. $start++;
  293. } else {
  294. $start = 1;
  295. $newRootId = $nodeId;
  296. }
  297. $diff = $start - $left;
  298. if (!$isNewNode) {
  299. $levelDiff = isset($config['level']) ? $level - $wrapped->getPropertyValue($config['level']) : null;
  300. $this->shiftRangeRL(
  301. $em,
  302. $config['useObjectClass'],
  303. $left,
  304. $right,
  305. $diff,
  306. $rootId,
  307. $newRootId,
  308. $levelDiff
  309. );
  310. $this->shiftRL($em, $config['useObjectClass'], $left, -$treeSize, $rootId);
  311. } else {
  312. $qb = $em->createQueryBuilder();
  313. $qb->update($config['useObjectClass'], 'node');
  314. if (isset($config['root'])) {
  315. $qb->set('node.' . $config['root'], $newRootId);
  316. $wrapped->setPropertyValue($config['root'], $newRootId);
  317. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['root'], $newRootId);
  318. }
  319. if (isset($config['level'])) {
  320. $qb->set('node.' . $config['level'], $level);
  321. $wrapped->setPropertyValue($config['level'], $level);
  322. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['level'], $level);
  323. }
  324. if (isset($newParent)) {
  325. $wrappedNewParent = AbstractWrapper::wrapp($newParent, $em);
  326. $newParentId = $wrappedNewParent->getIdentifier();
  327. $qb->set('node.' . $config['parent'], $newParentId);
  328. $wrapped->setPropertyValue($config['parent'], $newParent);
  329. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['parent'], $newParent);
  330. }
  331. $qb->set('node.' . $config['left'], $left + $diff);
  332. $qb->set('node.' . $config['right'], $right + $diff);
  333. $qb->where("node.{$identifierField} = {$nodeId}");
  334. $qb->getQuery()->getSingleScalarResult();
  335. $wrapped->setPropertyValue($config['left'], $left + $diff);
  336. $wrapped->setPropertyValue($config['right'], $right + $diff);
  337. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $diff);
  338. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $diff);
  339. }
  340. }
  341. /**
  342. * Get the edge of tree
  343. *
  344. * @param EntityManager $em
  345. * @param string $class
  346. * @param integer $rootId
  347. * @return integer
  348. */
  349. public function max(EntityManager $em, $class, $rootId = 0)
  350. {
  351. $meta = $em->getClassMetadata($class);
  352. $config = $this->listener->getConfiguration($em, $meta->name);
  353. $dql = "SELECT MAX(node.{$config['right']}) FROM {$config['useObjectClass']} node";
  354. if (isset($config['root']) && $rootId) {
  355. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  356. }
  357. $query = $em->createQuery($dql);
  358. $right = $query->getSingleScalarResult();
  359. return intval($right);
  360. }
  361. /**
  362. * Shift tree left and right values by delta
  363. *
  364. * @param EntityManager $em
  365. * @param string $class
  366. * @param integer $first
  367. * @param integer $delta
  368. * @param integer $rootId
  369. * @return void
  370. */
  371. public function shiftRL(EntityManager $em, $class, $first, $delta, $rootId = null)
  372. {
  373. $meta = $em->getClassMetadata($class);
  374. $config = $this->listener->getConfiguration($em, $class);
  375. $sign = ($delta >= 0) ? ' + ' : ' - ';
  376. $absDelta = abs($delta);
  377. $dql = "UPDATE {$meta->name} node";
  378. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$absDelta}";
  379. $dql .= " WHERE node.{$config['left']} >= {$first}";
  380. if (isset($config['root'])) {
  381. $dql .= " AND node.{$config['root']} = {$rootId}";
  382. }
  383. $q = $em->createQuery($dql);
  384. $q->getSingleScalarResult();
  385. $dql = "UPDATE {$meta->name} node";
  386. $dql .= " SET node.{$config['right']} = node.{$config['right']} {$sign} {$absDelta}";
  387. $dql .= " WHERE node.{$config['right']} >= {$first}";
  388. if (isset($config['root'])) {
  389. $dql .= " AND node.{$config['root']} = {$rootId}";
  390. }
  391. $q = $em->createQuery($dql);
  392. $q->getSingleScalarResult();
  393. // update in memory nodes increases performance, saves some IO
  394. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  395. // for inheritance mapped classes, only root is always in the identity map
  396. if ($className !== $meta->rootEntityName) {
  397. continue;
  398. }
  399. foreach ($nodes as $node) {
  400. if ($node instanceof Proxy && !$node->__isInitialized__) {
  401. continue;
  402. }
  403. $oid = spl_object_hash($node);
  404. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  405. $root = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  406. if ($root === $rootId && $left >= $first) {
  407. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  408. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  409. }
  410. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  411. if ($root === $rootId && $right >= $first) {
  412. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  413. $em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  414. }
  415. }
  416. }
  417. }
  418. /**
  419. * Shift range of right and left values on tree
  420. * depending on tree level diference also
  421. *
  422. * @param EntityManager $em
  423. * @param string $class
  424. * @param integer $first
  425. * @param integer $last
  426. * @param integer $delta
  427. * @param integer $rootId
  428. * @param integer $destRootId
  429. * @param integer $levelDelta
  430. * @return void
  431. */
  432. public function shiftRangeRL(EntityManager $em, $class, $first, $last, $delta, $rootId = null, $destRootId = null, $levelDelta = null)
  433. {
  434. $meta = $em->getClassMetadata($class);
  435. $config = $this->listener->getConfiguration($em, $class);
  436. $sign = ($delta >= 0) ? ' + ' : ' - ';
  437. $absDelta = abs($delta);
  438. $levelSign = ($levelDelta >= 0) ? ' + ' : ' - ';
  439. $absLevelDelta = abs($levelDelta);
  440. $dql = "UPDATE {$meta->name} node";
  441. $dql .= " SET node.{$config['left']} = node.{$config['left']} {$sign} {$absDelta}";
  442. $dql .= ", node.{$config['right']} = node.{$config['right']} {$sign} {$absDelta}";
  443. if (isset($config['root'])) {
  444. $dql .= ", node.{$config['root']} = {$destRootId}";
  445. }
  446. if (isset($config['level'])) {
  447. $dql .= ", node.{$config['level']} = node.{$config['level']} {$levelSign} {$absLevelDelta}";
  448. }
  449. $dql .= " WHERE node.{$config['left']} >= {$first}";
  450. $dql .= " AND node.{$config['right']} <= {$last}";
  451. if (isset($config['root'])) {
  452. $dql .= " AND node.{$config['root']} = {$rootId}";
  453. }
  454. $q = $em->createQuery($dql);
  455. $q->getSingleScalarResult();
  456. // update in memory nodes increases performance, saves some IO
  457. foreach ($em->getUnitOfWork()->getIdentityMap() as $className => $nodes) {
  458. // for inheritance mapped classes, only root is always in the identity map
  459. if ($className !== $meta->rootEntityName) {
  460. continue;
  461. }
  462. foreach ($nodes as $node) {
  463. if ($node instanceof Proxy && !$node->__isInitialized__) {
  464. continue;
  465. }
  466. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  467. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  468. $root = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($node) : null;
  469. if ($root === $rootId && $left >= $first && $right <= $last) {
  470. $oid = spl_object_hash($node);
  471. $uow = $em->getUnitOfWork();
  472. $meta->getReflectionProperty($config['left'])->setValue($node, $left + $delta);
  473. $uow->setOriginalEntityProperty($oid, $config['left'], $left + $delta);
  474. $meta->getReflectionProperty($config['right'])->setValue($node, $right + $delta);
  475. $uow->setOriginalEntityProperty($oid, $config['right'], $right + $delta);
  476. if (isset($config['root'])) {
  477. $meta->getReflectionProperty($config['root'])->setValue($node, $destRootId);
  478. $uow->setOriginalEntityProperty($oid, $config['root'], $destRootId);
  479. }
  480. if (isset($config['level'])) {
  481. $level = $meta->getReflectionProperty($config['level'])->getValue($node);
  482. $meta->getReflectionProperty($config['level'])->setValue($node, $level + $levelDelta);
  483. $uow->setOriginalEntityProperty($oid, $config['level'], $level + $levelDelta);
  484. }
  485. }
  486. }
  487. }
  488. }
  489. }