Closure.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Gedmo\Exception\RuntimeException;
  4. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  5. use Gedmo\Tree\Strategy;
  6. use Doctrine\ORM\EntityManager;
  7. use Doctrine\ORM\Proxy\Proxy;
  8. use Gedmo\Tree\TreeListener;
  9. /**
  10. * This strategy makes tree act like
  11. * a closure table.
  12. *
  13. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @package Gedmo.Tree.Strategy.ORM
  16. * @subpackage Closure
  17. * @link http://www.gediminasm.org
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. class Closure implements Strategy
  21. {
  22. /**
  23. * TreeListener
  24. *
  25. * @var AbstractTreeListener
  26. */
  27. protected $listener = null;
  28. /**
  29. * List of pending Nodes, which needs to
  30. * be post processed because of having a parent Node
  31. * which requires some additional calculations
  32. *
  33. * @var array
  34. */
  35. private $pendingChildNodeInserts = array();
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function __construct(TreeListener $listener)
  40. {
  41. $this->listener = $listener;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function getName()
  47. {
  48. return Strategy::CLOSURE;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function processMetadataLoad($em, $meta)
  54. {
  55. $config = $this->listener->getConfiguration($em, $meta->name);
  56. $closureMetadata = $em->getClassMetadata($config['closure']);
  57. // create ancestor mapping
  58. $ancestorMapping = array(
  59. 'fieldName' => 'ancestor',
  60. 'id' => false,
  61. 'joinColumns' => array(
  62. array(
  63. 'name' => 'ancestor',
  64. 'referencedColumnName' => 'id',
  65. 'unique' => false,
  66. 'nullable' => false,
  67. 'onDelete' => 'CASCADE',
  68. 'onUpdate' => null,
  69. 'columnDefinition' => null,
  70. )
  71. ),
  72. 'inversedBy' => null,
  73. 'targetEntity' => $meta->name,
  74. 'cascade' => null,
  75. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  76. );
  77. $closureMetadata->mapManyToOne($ancestorMapping);
  78. // create descendant mapping
  79. $descendantMapping = array(
  80. 'fieldName' => 'descendant',
  81. 'id' => false,
  82. 'joinColumns' => array(
  83. array(
  84. 'name' => 'descendant',
  85. 'referencedColumnName' => 'id',
  86. 'unique' => false,
  87. 'nullable' => false,
  88. 'onDelete' => 'CASCADE',
  89. 'onUpdate' => null,
  90. 'columnDefinition' => null,
  91. )
  92. ),
  93. 'inversedBy' => null,
  94. 'targetEntity' => $meta->name,
  95. 'cascade' => null,
  96. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  97. );
  98. $closureMetadata->mapManyToOne($descendantMapping);
  99. // create unique index on ancestor and descendant
  100. $indexName = substr(strtoupper("IDX_" . md5($closureMetadata->name)), 0, 20);
  101. $closureMetadata->table['uniqueConstraints'][$indexName] = array(
  102. 'columns' => array('ancestor', 'descendant')
  103. );
  104. // this one may not be very usefull
  105. $indexName = substr(strtoupper("IDX_" . md5($meta->name . 'depth')), 0, 20);
  106. $closureMetadata->table['indexes']['depth_index'] = array(
  107. 'columns' => array('depth')
  108. );
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function onFlushEnd($em)
  114. {}
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function processPrePersist($em, $node)
  119. {
  120. $this->pendingChildNodeInserts[spl_object_hash($node)] = $node;
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function processPreRemove($em, $node)
  126. {}
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function processScheduledInsertion($em, $node)
  131. {}
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function processScheduledDelete($em, $entity)
  136. {}
  137. /**
  138. * {@inheritdoc}
  139. */
  140. public function processPostPersist($em, $entity)
  141. {
  142. $uow = $em->getUnitOfWork();
  143. if ($uow->hasPendingInsertions()) {
  144. return;
  145. }
  146. while ($node = array_shift($this->pendingChildNodeInserts)) {
  147. $meta = $em->getClassMetadata(get_class($node));
  148. $config = $this->listener->getConfiguration($em, $meta->name);
  149. $identifier = $meta->getSingleIdentifierFieldName();
  150. $nodeId = $meta->getReflectionProperty($identifier)->getValue($node);
  151. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  152. $closureClass = $config['closure'];
  153. $closureMeta = $em->getClassMetadata($closureClass);
  154. $closureTable = $closureMeta->getTableName();
  155. $entries = array(
  156. array(
  157. 'ancestor' => $nodeId,
  158. 'descendant' => $nodeId,
  159. 'depth' => 0
  160. )
  161. );
  162. if ($parent) {
  163. $dql = "SELECT c, a FROM {$closureMeta->name} c";
  164. $dql .= " JOIN c.ancestor a";
  165. $dql .= " WHERE c.descendant = :parent";
  166. $q = $em->createQuery($dql);
  167. $q->setParameters(compact('parent'));
  168. $ancestors = $q->getArrayResult();
  169. foreach ($ancestors as $ancestor) {
  170. $entries[] = array(
  171. 'ancestor' => $ancestor['ancestor']['id'],
  172. 'descendant' => $nodeId,
  173. 'depth' => $ancestor['depth'] + 1
  174. );
  175. }
  176. }
  177. foreach ($entries as $closure) {
  178. if (!$em->getConnection()->insert($closureTable, $closure)) {
  179. throw new RuntimeException('Failed to insert new Closure record');
  180. }
  181. }
  182. }
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. public function processScheduledUpdate($em, $node)
  188. {
  189. $meta = $em->getClassMetadata(get_class($node));
  190. $config = $this->listener->getConfiguration($em, $meta->name);
  191. $uow = $em->getUnitOfWork();
  192. $changeSet = $uow->getEntityChangeSet($node);
  193. if (array_key_exists($config['parent'], $changeSet)) {
  194. $this->updateNode($em, $node, $changeSet[$config['parent']][0]);
  195. }
  196. }
  197. /**
  198. * Update node and closures
  199. *
  200. * @param EntityManager $em
  201. * @param object $node
  202. * @param object $oldParent
  203. */
  204. public function updateNode(EntityManager $em, $node, $oldParent)
  205. {
  206. $meta = $em->getClassMetadata(get_class($node));
  207. $config = $this->listener->getConfiguration($em, $meta->name);
  208. $closureMeta = $em->getClassMetadata($config['closure']);
  209. $nodeId = $this->extractIdentifier($em, $node);
  210. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  211. $table = $closureMeta->getTableName();
  212. $conn = $em->getConnection();
  213. // ensure integrity
  214. if ($parent) {
  215. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  216. $dql .= " WHERE c.ancestor = :node";
  217. $dql .= " AND c.descendant = :parent";
  218. $q = $em->createQuery($dql);
  219. $q->setParameters(compact('node', 'parent'));
  220. if ($q->getSingleScalarResult()) {
  221. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  222. }
  223. }
  224. if ($oldParent) {
  225. $subQuery = "SELECT c2.id FROM {$table} c1";
  226. $subQuery .= " JOIN {$table} c2 ON c1.descendant = c2.descendant";
  227. $subQuery .= " WHERE c1.ancestor = :nodeId AND c2.depth > c1.depth";
  228. $ids = $conn->fetchAll($subQuery, compact('nodeId'));
  229. if ($ids) {
  230. $ids = array_map(function($el) {
  231. return $el['id'];
  232. }, $ids);
  233. }
  234. // using subquery directly, sqlite acts unfriendly
  235. $query = "DELETE FROM {$table} WHERE id IN (".implode(', ', $ids).")";
  236. if (!$conn->executeQuery($query)) {
  237. throw new RuntimeException('Failed to remove old closures');
  238. }
  239. }
  240. if ($parent) {
  241. $parentId = $this->extractIdentifier($em, $parent);
  242. $query = "SELECT c1.ancestor, c2.descendant, (c1.depth + c2.depth + 1) AS depth";
  243. $query .= " FROM {$table} c1, {$table} c2";
  244. $query .= " WHERE c1.descendant = :parentId";
  245. $query .= " AND c2.ancestor = :nodeId";
  246. $closures = $conn->fetchAll($query, compact('nodeId', 'parentId'));
  247. foreach ($closures as $closure) {
  248. if (!$conn->insert($table, $closure)) {
  249. throw new RuntimeException('Failed to insert new Closure record');
  250. }
  251. }
  252. }
  253. }
  254. /**
  255. * Extracts identifiers from object or proxy
  256. *
  257. * @param EntityManager $em
  258. * @param object $entity
  259. * @param bool $single
  260. * @return mixed - array or single identifier
  261. */
  262. private function extractIdentifier(EntityManager $em, $entity, $single = true)
  263. {
  264. if ($entity instanceof Proxy) {
  265. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  266. } else {
  267. $meta = $em->getClassMetadata(get_class($entity));
  268. $id = array();
  269. foreach ($meta->identifier as $name) {
  270. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  271. }
  272. }
  273. if ($single) {
  274. $id = current($id);
  275. }
  276. return $id;
  277. }
  278. }