Closure.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Gedmo\Tree\Strategy,
  4. Doctrine\ORM\EntityManager,
  5. Doctrine\ORM\Proxy\Proxy,
  6. Gedmo\Tree\AbstractTreeListener;
  7. /**
  8. * This strategy makes tree act like
  9. * a closure table.
  10. *
  11. * Some Tree logic is copied from -
  12. * CakePHP: Rapid Development Framework (http://cakephp.org)
  13. *
  14. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  15. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  16. * @package Gedmo.Tree.Strategy.ORM
  17. * @subpackage Closure
  18. * @link http://www.gediminasm.org
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. class Closure implements Strategy
  22. {
  23. /**
  24. * TreeListener
  25. *
  26. * @var AbstractTreeListener
  27. */
  28. protected $listener = null;
  29. /**
  30. * List of pending Nodes, which needs to
  31. * be post processed because of having a parent Node
  32. * which requires some additional calculations
  33. *
  34. * @var array
  35. */
  36. protected $pendingChildNodeInserts = array();
  37. /**
  38. * List of pending Nodes to remove
  39. *
  40. * @var array
  41. */
  42. protected $pendingNodesForRemove = array();
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function __construct(AbstractTreeListener $listener)
  47. {
  48. $this->listener = $listener;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function getName()
  54. {
  55. return Strategy::CLOSURE;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function processPrePersist($em, $entity)
  61. {
  62. $this->pendingChildNodeInserts[] = $entity;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function processPostPersist($em, $entity)
  68. {
  69. if (count($this->pendingChildNodeInserts))
  70. {
  71. while ($entity = array_shift($this->pendingChildNodeInserts))
  72. {
  73. $this->insertNode($em, $entity);
  74. }
  75. }
  76. }
  77. public function insertNode(EntityManager $em, $entity, $addNodeChildrenToAncestors = false)
  78. {
  79. $meta = $em->getClassMetadata(get_class($entity));
  80. $config = $this->listener->getConfiguration($em, $meta->name);
  81. $identifier = $meta->getSingleIdentifierFieldName();
  82. $id = $meta->getReflectionProperty($identifier)->getValue($entity);
  83. $closureMeta = $em->getClassMetadata($config['closure']);
  84. $entries = array();
  85. // If node has children it means it already has a self referencing row, so we skip its insertion
  86. if ($addNodeChildrenToAncestors === false) {
  87. $entries[] = array(
  88. 'ancestor' => $id,
  89. 'descendant' => $id,
  90. 'depth' => 0
  91. );
  92. }
  93. $parent = $meta->getReflectionProperty($config['parent'])->getValue($entity);
  94. if ( $parent ) {
  95. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  96. $dql = "SELECT c.ancestor, c.depth FROM {$closureMeta->name} c";
  97. $dql .= " WHERE c.descendant = {$parentId}";
  98. $ancestors = $em->createQuery($dql)->getArrayResult();
  99. //echo count($ancestors);
  100. foreach ($ancestors as $ancestor) {
  101. $entries[] = array(
  102. 'ancestor' => $ancestor['ancestor'],
  103. 'descendant' => $id,
  104. 'depth' => $ancestor['depth'] + 1
  105. );
  106. if ($addNodeChildrenToAncestors === true) {
  107. $dql = "SELECT c.descendant, c.depth FROM {$closureMeta->name} c";
  108. $dql .= " WHERE c.ancestor = {$id} AND c.ancestor != c.descendant";
  109. $children = $em->createQuery($dql)
  110. ->getArrayResult();
  111. foreach ($children as $child)
  112. {
  113. $entries[] = array(
  114. 'ancestor' => $ancestor['ancestor'],
  115. 'descendant' => $child['descendant'],
  116. 'depth' => $child['depth'] + 1
  117. );
  118. }
  119. }
  120. }
  121. }
  122. $table = $closureMeta->getTableName();
  123. foreach ($entries as $closure) {
  124. if (!$em->getConnection()->insert($table, $closure)) {
  125. throw new \Gedmo\Exception\RuntimeException('Failed to insert new Closure record');
  126. }
  127. }
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function processScheduledUpdate($em, $entity)
  133. {
  134. $entityClass = get_class($entity);
  135. $config = $this->listener->getConfiguration($em, $entityClass);
  136. $meta = $em->getClassMetadata($entityClass);
  137. $uow = $em->getUnitOfWork();
  138. $changeSet = $uow->getEntityChangeSet($entity);
  139. if (array_key_exists($config['parent'], $changeSet)) {
  140. $this->updateNode($em, $entity, $changeSet[$config['parent']]);
  141. }
  142. }
  143. public function updateNode(EntityManager $em, $entity, array $change)
  144. {
  145. $meta = $em->getClassMetadata(get_class($entity));
  146. $config = $this->listener->getConfiguration($em, $meta->name);
  147. $closureMeta = $em->getClassMetadata($config['closure']);
  148. $oldParent = $change[0];
  149. $nodeId = $this->extractIdentifier($em, $entity);
  150. $table = $closureMeta->getTableName();
  151. if ($oldParent)
  152. {
  153. $this->removeClosurePathsOfNodeID($em, $table, $nodeId);
  154. $this->insertNode($em, $entity, true);
  155. }
  156. //\Doctrine\Common\Util\Debug::dump($oldParent);
  157. //die();
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function processScheduledDelete($em, $entity)
  163. {
  164. $this->removeNode($em, $entity);
  165. }
  166. public function removeNode(EntityManager $em, $entity, $maintainSelfReferencingRow = false, $maintainSelfReferencingRowOfChildren = false)
  167. {
  168. $meta = $em->getClassMetadata(get_class($entity));
  169. $config = $this->listener->getConfiguration($em, $meta->name);
  170. $closureMeta = $em->getClassMetadata($config['closure']);
  171. $this->removeClosurePathsOfNodeID($em, $closureMeta->getTableName(), $entity->getId(), $maintainSelfReferencingRow, $maintainSelfReferencingRowOfChildren);
  172. }
  173. public function removeClosurePathsOfNodeID(EntityManager $em, $table, $nodeId, $maintainSelfReferencingRow = true, $maintainSelfReferencingRowOfChildren = true)
  174. {
  175. $subquery = "SELECT c1.id FROM {$table} c1 ";
  176. $subquery .= "WHERE c1.descendant IN ( SELECT c2.descendant FROM {$table} c2 WHERE c2.ancestor = :id ) ";
  177. $subquery .= "AND ( c1.ancestor IN ( SELECT c3.ancestor FROM {$table} c3 WHERE c3.descendant = :id ";
  178. if ($maintainSelfReferencingRow === true)
  179. {
  180. $subquery .= "AND c3.descendant != c3.ancestor ";
  181. }
  182. if ( $maintainSelfReferencingRowOfChildren === false )
  183. {
  184. $subquery .= " OR c1.descendant = c1.ancestor ";
  185. }
  186. $subquery .= " ) ) ";
  187. $subquery = "DELETE FROM {$table} WHERE {$table}.id IN ( SELECT temp_table.id FROM ( {$subquery} ) temp_table )";
  188. if (!$em->getConnection()->executeQuery($subquery, array('id' => $nodeId))) {
  189. throw new \Gedmo\Exception\RuntimeException('Failed to delete old Closure records');
  190. }
  191. }
  192. private function extractIdentifier($em, $entity, $single = true)
  193. {
  194. if ($entity instanceof Proxy) {
  195. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  196. } else {
  197. $meta = $em->getClassMetadata(get_class($entity));
  198. $id = array();
  199. foreach ($meta->identifier as $name) {
  200. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  201. }
  202. }
  203. if ($single) {
  204. $id = current($id);
  205. }
  206. return $id;
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function onFlushEnd($em)
  212. {}
  213. }