Closure.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. if (!$closureMetadata->hasAssociation('ancestor')) {
  58. // create ancestor mapping
  59. $ancestorMapping = array(
  60. 'fieldName' => 'ancestor',
  61. 'id' => false,
  62. 'joinColumns' => array(
  63. array(
  64. 'name' => 'ancestor',
  65. 'referencedColumnName' => 'id',
  66. 'unique' => false,
  67. 'nullable' => false,
  68. 'onDelete' => 'CASCADE',
  69. 'onUpdate' => null,
  70. 'columnDefinition' => null,
  71. )
  72. ),
  73. 'inversedBy' => null,
  74. 'targetEntity' => $meta->name,
  75. 'cascade' => null,
  76. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  77. );
  78. $closureMetadata->mapManyToOne($ancestorMapping);
  79. }
  80. if (!$closureMetadata->hasAssociation('descendant')) {
  81. // create descendant mapping
  82. $descendantMapping = array(
  83. 'fieldName' => 'descendant',
  84. 'id' => false,
  85. 'joinColumns' => array(
  86. array(
  87. 'name' => 'descendant',
  88. 'referencedColumnName' => 'id',
  89. 'unique' => false,
  90. 'nullable' => false,
  91. 'onDelete' => 'CASCADE',
  92. 'onUpdate' => null,
  93. 'columnDefinition' => null,
  94. )
  95. ),
  96. 'inversedBy' => null,
  97. 'targetEntity' => $meta->name,
  98. 'cascade' => null,
  99. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  100. );
  101. $closureMetadata->mapManyToOne($descendantMapping);
  102. }
  103. // create unique index on ancestor and descendant
  104. $indexName = substr(strtoupper("IDX_" . md5($closureMetadata->name)), 0, 20);
  105. $closureMetadata->table['uniqueConstraints'][$indexName] = array(
  106. 'columns' => array('ancestor', 'descendant')
  107. );
  108. // this one may not be very usefull
  109. $indexName = substr(strtoupper("IDX_" . md5($meta->name . 'depth')), 0, 20);
  110. $closureMetadata->table['indexes'][$indexName] = array(
  111. 'columns' => array('depth')
  112. );
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function onFlushEnd($em)
  118. {}
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function processPrePersist($em, $node)
  123. {
  124. $this->pendingChildNodeInserts[spl_object_hash($node)] = $node;
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. public function processPreRemove($em, $node)
  130. {}
  131. /**
  132. * {@inheritdoc}
  133. */
  134. public function processScheduledInsertion($em, $node)
  135. {}
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function processScheduledDelete($em, $entity)
  140. {}
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function processPostPersist($em, $entity)
  145. {
  146. $uow = $em->getUnitOfWork();
  147. if ($uow->hasPendingInsertions()) {
  148. return;
  149. }
  150. while ($node = array_shift($this->pendingChildNodeInserts)) {
  151. $meta = $em->getClassMetadata(get_class($node));
  152. $config = $this->listener->getConfiguration($em, $meta->name);
  153. $identifier = $meta->getSingleIdentifierFieldName();
  154. $nodeId = $meta->getReflectionProperty($identifier)->getValue($node);
  155. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  156. $closureClass = $config['closure'];
  157. $closureMeta = $em->getClassMetadata($closureClass);
  158. $closureTable = $closureMeta->getTableName();
  159. $entries = array(
  160. array(
  161. 'ancestor' => $nodeId,
  162. 'descendant' => $nodeId,
  163. 'depth' => 0
  164. )
  165. );
  166. if ($parent) {
  167. $dql = "SELECT c, a FROM {$closureMeta->name} c";
  168. $dql .= " JOIN c.ancestor a";
  169. $dql .= " WHERE c.descendant = :parent";
  170. $q = $em->createQuery($dql);
  171. $q->setParameters(compact('parent'));
  172. $ancestors = $q->getArrayResult();
  173. foreach ($ancestors as $ancestor) {
  174. $entries[] = array(
  175. 'ancestor' => $ancestor['ancestor']['id'],
  176. 'descendant' => $nodeId,
  177. 'depth' => $ancestor['depth'] + 1
  178. );
  179. }
  180. }
  181. foreach ($entries as $closure) {
  182. if (!$em->getConnection()->insert($closureTable, $closure)) {
  183. throw new RuntimeException('Failed to insert new Closure record');
  184. }
  185. }
  186. }
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function processScheduledUpdate($em, $node)
  192. {
  193. $meta = $em->getClassMetadata(get_class($node));
  194. $config = $this->listener->getConfiguration($em, $meta->name);
  195. $uow = $em->getUnitOfWork();
  196. $changeSet = $uow->getEntityChangeSet($node);
  197. if (array_key_exists($config['parent'], $changeSet)) {
  198. $this->updateNode($em, $node, $changeSet[$config['parent']][0]);
  199. }
  200. }
  201. /**
  202. * Update node and closures
  203. *
  204. * @param EntityManager $em
  205. * @param object $node
  206. * @param object $oldParent
  207. */
  208. public function updateNode(EntityManager $em, $node, $oldParent)
  209. {
  210. $meta = $em->getClassMetadata(get_class($node));
  211. $config = $this->listener->getConfiguration($em, $meta->name);
  212. $closureMeta = $em->getClassMetadata($config['closure']);
  213. $nodeId = $this->extractIdentifier($em, $node);
  214. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  215. $table = $closureMeta->getTableName();
  216. $conn = $em->getConnection();
  217. // ensure integrity
  218. if ($parent) {
  219. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  220. $dql .= " WHERE c.ancestor = :node";
  221. $dql .= " AND c.descendant = :parent";
  222. $q = $em->createQuery($dql);
  223. $q->setParameters(compact('node', 'parent'));
  224. if ($q->getSingleScalarResult()) {
  225. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  226. }
  227. }
  228. if ($oldParent) {
  229. $subQuery = "SELECT c2.id FROM {$table} c1";
  230. $subQuery .= " JOIN {$table} c2 ON c1.descendant = c2.descendant";
  231. $subQuery .= " WHERE c1.ancestor = :nodeId AND c2.depth > c1.depth";
  232. $ids = $conn->fetchAll($subQuery, compact('nodeId'));
  233. if ($ids) {
  234. $ids = array_map(function($el) {
  235. return $el['id'];
  236. }, $ids);
  237. }
  238. // using subquery directly, sqlite acts unfriendly
  239. $query = "DELETE FROM {$table} WHERE id IN (".implode(', ', $ids).")";
  240. if (!$conn->executeQuery($query)) {
  241. throw new RuntimeException('Failed to remove old closures');
  242. }
  243. }
  244. if ($parent) {
  245. $parentId = $this->extractIdentifier($em, $parent);
  246. $query = "SELECT c1.ancestor, c2.descendant, (c1.depth + c2.depth + 1) AS depth";
  247. $query .= " FROM {$table} c1, {$table} c2";
  248. $query .= " WHERE c1.descendant = :parentId";
  249. $query .= " AND c2.ancestor = :nodeId";
  250. $closures = $conn->fetchAll($query, compact('nodeId', 'parentId'));
  251. foreach ($closures as $closure) {
  252. if (!$conn->insert($table, $closure)) {
  253. throw new RuntimeException('Failed to insert new Closure record');
  254. }
  255. }
  256. }
  257. }
  258. /**
  259. * Extracts identifiers from object or proxy
  260. *
  261. * @param EntityManager $em
  262. * @param object $entity
  263. * @param bool $single
  264. * @return mixed - array or single identifier
  265. */
  266. private function extractIdentifier(EntityManager $em, $entity, $single = true)
  267. {
  268. if ($entity instanceof Proxy) {
  269. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  270. } else {
  271. $meta = $em->getClassMetadata(get_class($entity));
  272. $id = array();
  273. foreach ($meta->identifier as $name) {
  274. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  275. }
  276. }
  277. if ($single) {
  278. $id = current($id);
  279. }
  280. return $id;
  281. }
  282. }