Nested.php 21 KB

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