Closure.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  12. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  13. * @package Gedmo.Tree.Strategy.ORM
  14. * @subpackage Closure
  15. * @link http://www.gediminasm.org
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. class Closure implements Strategy
  19. {
  20. /**
  21. * TreeListener
  22. *
  23. * @var AbstractTreeListener
  24. */
  25. protected $listener = null;
  26. /**
  27. * List of pending Nodes, which needs to
  28. * be post processed because of having a parent Node
  29. * which requires some additional calculations
  30. *
  31. * @var array
  32. */
  33. protected $pendingChildNodeInserts = array();
  34. /**
  35. * List of pending Nodes to remove
  36. *
  37. * @var array
  38. */
  39. protected $pendingNodesForRemove = array();
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function __construct(AbstractTreeListener $listener)
  44. {
  45. $this->listener = $listener;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function getName()
  51. {
  52. return Strategy::CLOSURE;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function processPrePersist($em, $entity)
  58. {
  59. $this->pendingChildNodeInserts[] = $entity;
  60. $meta = $em->getClassMetadata(get_class($entity));
  61. $config = $this->listener->getConfiguration($em, $meta->name);
  62. if (isset( $config['childCount'])) {
  63. // We set by default 0 on insertions for childCount field
  64. $meta->getReflectionProperty($config['childCount'])->setValue($entity, 0);
  65. }
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function processPostPersist($em, $entity)
  71. {
  72. if (count($this->pendingChildNodeInserts)) {
  73. while ($e = array_shift($this->pendingChildNodeInserts)) {
  74. $this->insertNode($em, $e);
  75. }
  76. // If "childCount" property is in the schema, we recalculate child count of all entities
  77. $meta = $em->getClassMetadata(get_class($entity));
  78. $config = $this->listener->getConfiguration($em, $meta->name);
  79. if (isset($config['childCount'])) {
  80. $this->recalculateChildCountForEntities($em, get_class($entity));
  81. }
  82. }
  83. }
  84. /**
  85. * Insert node and closures
  86. *
  87. * @param EntityManager $em
  88. * @param object $entity
  89. * @param bool $addNodeChildrenToAncestors
  90. * @throws \Gedmo\Exception\RuntimeException - if closure insert fails
  91. */
  92. public function insertNode(EntityManager $em, $entity, $addNodeChildrenToAncestors = false)
  93. {
  94. $meta = $em->getClassMetadata(get_class($entity));
  95. $config = $this->listener->getConfiguration($em, $meta->name);
  96. $identifier = $meta->getSingleIdentifierFieldName();
  97. $id = $this->extractIdentifier($em, $entity);
  98. $closureMeta = $em->getClassMetadata($config['closure']);
  99. $entityTable = $meta->getTableName();
  100. $closureTable = $closureMeta->getTableName();
  101. $entries = array();
  102. $childrenIDs = array();
  103. $ancestorsIDs = array();
  104. // If node has children it means it already has a self referencing row, so we skip its insertion
  105. if ($addNodeChildrenToAncestors === false) {
  106. $entries[] = array(
  107. 'ancestor' => $id,
  108. 'descendant' => $id,
  109. 'depth' => 0
  110. );
  111. }
  112. $parent = $meta->getReflectionProperty($config['parent'])->getValue($entity);
  113. if ($parent) {
  114. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  115. $dql = "SELECT c.ancestor, c.depth FROM {$closureMeta->name} c";
  116. $dql .= " WHERE c.descendant = {$parentId}";
  117. $ancestors = $em->createQuery($dql)->getArrayResult();
  118. foreach ($ancestors as $ancestor) {
  119. $entries[] = array(
  120. 'ancestor' => $ancestor['ancestor'],
  121. 'descendant' => $id,
  122. 'depth' => $ancestor['depth'] + 1
  123. );
  124. $ancestorsIDs[] = $ancestor['ancestor'];
  125. if ($addNodeChildrenToAncestors === true) {
  126. $dql = "SELECT c.descendant, c.depth FROM {$closureMeta->name} c";
  127. $dql .= " WHERE c.ancestor = {$id} AND c.ancestor != c.descendant";
  128. $children = $em->createQuery($dql)
  129. ->getArrayResult();
  130. foreach ($children as $child) {
  131. $entries[] = array(
  132. 'ancestor' => $ancestor['ancestor'],
  133. 'descendant' => $child['descendant'],
  134. 'depth' => $child['depth'] + 1
  135. );
  136. $childrenIDs[] = $child['descendant'];
  137. }
  138. }
  139. }
  140. }
  141. foreach ($entries as $closure) {
  142. if (!$em->getConnection()->insert($closureTable, $closure)) {
  143. throw new \Gedmo\Exception\RuntimeException('Failed to insert new Closure record');
  144. }
  145. }
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. public function processScheduledUpdate($em, $entity)
  151. {
  152. $entityClass = get_class($entity);
  153. $config = $this->listener->getConfiguration($em, $entityClass);
  154. $meta = $em->getClassMetadata($entityClass);
  155. $uow = $em->getUnitOfWork();
  156. $changeSet = $uow->getEntityChangeSet($entity);
  157. if (array_key_exists($config['parent'], $changeSet)) {
  158. $this->updateNode($em, $entity, $changeSet[$config['parent']]);
  159. }
  160. // If "childCount" property is in the schema, we recalculate child count of all entities
  161. if (isset($config['childCount'])) {
  162. $this->recalculateChildCountForEntities($em, get_class($entity));
  163. }
  164. }
  165. /**
  166. * Update node and closures
  167. *
  168. * @param EntityManager $em
  169. * @param object $entity
  170. * @param array $change - changeset of parent
  171. */
  172. public function updateNode(EntityManager $em, $entity, array $change)
  173. {
  174. $meta = $em->getClassMetadata(get_class($entity));
  175. $config = $this->listener->getConfiguration($em, $meta->name);
  176. $closureMeta = $em->getClassMetadata($config['closure']);
  177. $oldParent = $change[0];
  178. $nodeId = $this->extractIdentifier($em, $entity);
  179. $table = $closureMeta->getTableName();
  180. if ($oldParent) {
  181. $this->removeClosurePathsOfNodeID($em, $table, $nodeId);
  182. $this->insertNode($em, $entity, true);
  183. }
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function processScheduledDelete($em, $entity)
  189. {
  190. $this->removeNode($em, $entity);
  191. // If "childCount" property is in the schema, we recalculate child count of all entities
  192. $meta = $em->getClassMetadata(get_class($entity));
  193. $config = $this->listener->getConfiguration($em, $meta->name);
  194. if (isset($config['childCount'])) {
  195. $this->recalculateChildCountForEntities($em, get_class( $entity ));
  196. }
  197. }
  198. /**
  199. * Remove node and associated closures
  200. *
  201. * @param EntityManager $em
  202. * @param object $entity
  203. * @param bool $maintainSelfReferencingRow
  204. * @param bool $maintainSelfReferencingRowOfChildren
  205. */
  206. public function removeNode(EntityManager $em, $entity, $maintainSelfReferencingRow = false, $maintainSelfReferencingRowOfChildren = false)
  207. {
  208. $meta = $em->getClassMetadata(get_class($entity));
  209. $config = $this->listener->getConfiguration($em, $meta->name);
  210. $closureMeta = $em->getClassMetadata($config['closure']);
  211. $id = $this->extractIdentifier($em, $entity);
  212. $this->removeClosurePathsOfNodeID($em, $closureMeta->getTableName(), $id, $maintainSelfReferencingRow, $maintainSelfReferencingRowOfChildren);
  213. }
  214. /**
  215. * Remove closures for node $nodeId
  216. *
  217. * @param EntityManager $em
  218. * @param string $table
  219. * @param integer $nodeId
  220. * @param bool $maintainSelfReferencingRow
  221. * @param bool $maintainSelfReferencingRowOfChildren
  222. * @throws \Gedmo\Exception\RuntimeException - if deletion of closures fails
  223. */
  224. public function removeClosurePathsOfNodeID(EntityManager $em, $table, $nodeId, $maintainSelfReferencingRow = true, $maintainSelfReferencingRowOfChildren = true)
  225. {
  226. $subquery = "SELECT c1.id FROM {$table} c1 ";
  227. $subquery .= "WHERE c1.descendant IN (SELECT c2.descendant FROM {$table} c2 WHERE c2.ancestor = :id) ";
  228. $subquery .= "AND (c1.ancestor IN (SELECT c3.ancestor FROM {$table} c3 WHERE c3.descendant = :id ";
  229. if ($maintainSelfReferencingRow === true) {
  230. $subquery .= "AND c3.descendant != c3.ancestor ";
  231. }
  232. if ( $maintainSelfReferencingRowOfChildren === false) {
  233. $subquery .= " OR c1.descendant = c1.ancestor ";
  234. }
  235. $subquery .= " )) ";
  236. $subquery = "DELETE FROM {$table} WHERE {$table}.id IN (SELECT temp_table.id FROM ({$subquery}) temp_table)";
  237. if (!$em->getConnection()->executeQuery($subquery, array('id' => $nodeId))) {
  238. throw new \Gedmo\Exception\RuntimeException('Failed to delete old Closure records');
  239. }
  240. }
  241. /**
  242. * Childcount recalculation
  243. *
  244. * @param EntityManager $em
  245. * @param string $entityClass
  246. * @throws \Gedmo\Exception\RuntimeException - if update fails
  247. */
  248. public function recalculateChildCountForEntities(EntityManager $em, $entityClass)
  249. {
  250. $meta = $em->getClassMetadata($entityClass);
  251. $config = $this->listener->getConfiguration($em, $meta->name);
  252. $entityIdentifierField = $meta->getIdentifierColumnNames();
  253. $entityIdentifierField = $entityIdentifierField[0];
  254. $childCountField = $config['childCount'];
  255. $closureMeta = $em->getClassMetadata($config['closure']);
  256. $entityTable = $meta->getTableName();
  257. $closureTable = $closureMeta->getTableName();
  258. $subquery = "(SELECT COUNT( c2.descendant ) FROM {$closureTable} c2 WHERE c2.ancestor = c1.{$entityIdentifierField} AND c2.ancestor != c2.descendant)";
  259. $sql = "UPDATE {$entityTable} c1 SET c1.{$childCountField} = {$subquery}";
  260. if (!$em->getConnection()->executeQuery($sql)) {
  261. throw new \Gedmo\Exception\RuntimeException('Failed to update child count field of entities');
  262. }
  263. }
  264. /**
  265. * Extracts identifiers from object or proxy
  266. *
  267. * @param EntityManager $em
  268. * @param object $entity
  269. * @param bool $single
  270. * @return mixed - array or single identifier
  271. */
  272. private function extractIdentifier(EntityManager $em, $entity, $single = true)
  273. {
  274. if ($entity instanceof Proxy) {
  275. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  276. } else {
  277. $meta = $em->getClassMetadata(get_class($entity));
  278. $id = array();
  279. foreach ($meta->identifier as $name) {
  280. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  281. }
  282. }
  283. if ($single) {
  284. $id = current($id);
  285. }
  286. return $id;
  287. }
  288. /**
  289. * {@inheritdoc}
  290. */
  291. public function onFlushEnd($em)
  292. {
  293. }
  294. }