Nested.php 21 KB

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