Closure.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. if ($cacheDriver = $em->getMetadataFactory()->getCacheDriver()) {
  114. $cacheDriver->save($closureMetadata->name."\$CLASSMETADATA", $closureMetadata, null);
  115. }
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function onFlushEnd($em)
  121. {}
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function processPrePersist($em, $node)
  126. {
  127. $this->pendingChildNodeInserts[spl_object_hash($node)] = $node;
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function processPreRemove($em, $node)
  133. {}
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function processScheduledInsertion($em, $node)
  138. {}
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function processScheduledDelete($em, $entity)
  143. {}
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function processPostPersist($em, $entity)
  148. {
  149. $uow = $em->getUnitOfWork();
  150. if ($uow->hasPendingInsertions()) {
  151. return;
  152. }
  153. while ($node = array_shift($this->pendingChildNodeInserts)) {
  154. $meta = $em->getClassMetadata(get_class($node));
  155. $config = $this->listener->getConfiguration($em, $meta->name);
  156. $identifier = $meta->getSingleIdentifierFieldName();
  157. $nodeId = $meta->getReflectionProperty($identifier)->getValue($node);
  158. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  159. $closureClass = $config['closure'];
  160. $closureMeta = $em->getClassMetadata($closureClass);
  161. $closureTable = $closureMeta->getTableName();
  162. $entries = array(
  163. array(
  164. 'ancestor' => $nodeId,
  165. 'descendant' => $nodeId,
  166. 'depth' => 0
  167. )
  168. );
  169. if ($parent) {
  170. $dql = "SELECT c, a FROM {$closureMeta->name} c";
  171. $dql .= " JOIN c.ancestor a";
  172. $dql .= " WHERE c.descendant = :parent";
  173. $q = $em->createQuery($dql);
  174. $q->setParameters(compact('parent'));
  175. $ancestors = $q->getArrayResult();
  176. foreach ($ancestors as $ancestor) {
  177. $entries[] = array(
  178. 'ancestor' => $ancestor['ancestor']['id'],
  179. 'descendant' => $nodeId,
  180. 'depth' => $ancestor['depth'] + 1
  181. );
  182. }
  183. }
  184. foreach ($entries as $closure) {
  185. if (!$em->getConnection()->insert($closureTable, $closure)) {
  186. throw new RuntimeException('Failed to insert new Closure record');
  187. }
  188. }
  189. }
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function processScheduledUpdate($em, $node)
  195. {
  196. $meta = $em->getClassMetadata(get_class($node));
  197. $config = $this->listener->getConfiguration($em, $meta->name);
  198. $uow = $em->getUnitOfWork();
  199. $changeSet = $uow->getEntityChangeSet($node);
  200. if (array_key_exists($config['parent'], $changeSet)) {
  201. $this->updateNode($em, $node, $changeSet[$config['parent']][0]);
  202. }
  203. }
  204. /**
  205. * Update node and closures
  206. *
  207. * @param EntityManager $em
  208. * @param object $node
  209. * @param object $oldParent
  210. */
  211. public function updateNode(EntityManager $em, $node, $oldParent)
  212. {
  213. $meta = $em->getClassMetadata(get_class($node));
  214. $config = $this->listener->getConfiguration($em, $meta->name);
  215. $closureMeta = $em->getClassMetadata($config['closure']);
  216. $nodeId = $this->extractIdentifier($em, $node);
  217. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  218. $table = $closureMeta->getTableName();
  219. $conn = $em->getConnection();
  220. // ensure integrity
  221. if ($parent) {
  222. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  223. $dql .= " WHERE c.ancestor = :node";
  224. $dql .= " AND c.descendant = :parent";
  225. $q = $em->createQuery($dql);
  226. $q->setParameters(compact('node', 'parent'));
  227. if ($q->getSingleScalarResult()) {
  228. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  229. }
  230. }
  231. if ($oldParent) {
  232. $subQuery = "SELECT c2.id FROM {$table} c1";
  233. $subQuery .= " JOIN {$table} c2 ON c1.descendant = c2.descendant";
  234. $subQuery .= " WHERE c1.ancestor = :nodeId AND c2.depth > c1.depth";
  235. $ids = $conn->fetchAll($subQuery, compact('nodeId'));
  236. if ($ids) {
  237. $ids = array_map(function($el) {
  238. return $el['id'];
  239. }, $ids);
  240. }
  241. // using subquery directly, sqlite acts unfriendly
  242. $query = "DELETE FROM {$table} WHERE id IN (".implode(', ', $ids).")";
  243. if (!$conn->executeQuery($query)) {
  244. throw new RuntimeException('Failed to remove old closures');
  245. }
  246. }
  247. if ($parent) {
  248. $parentId = $this->extractIdentifier($em, $parent);
  249. $query = "SELECT c1.ancestor, c2.descendant, (c1.depth + c2.depth + 1) AS depth";
  250. $query .= " FROM {$table} c1, {$table} c2";
  251. $query .= " WHERE c1.descendant = :parentId";
  252. $query .= " AND c2.ancestor = :nodeId";
  253. $closures = $conn->fetchAll($query, compact('nodeId', 'parentId'));
  254. foreach ($closures as $closure) {
  255. if (!$conn->insert($table, $closure)) {
  256. throw new RuntimeException('Failed to insert new Closure record');
  257. }
  258. }
  259. }
  260. }
  261. /**
  262. * Extracts identifiers from object or proxy
  263. *
  264. * @param EntityManager $em
  265. * @param object $entity
  266. * @param bool $single
  267. * @return mixed - array or single identifier
  268. */
  269. private function extractIdentifier(EntityManager $em, $entity, $single = true)
  270. {
  271. if ($entity instanceof Proxy) {
  272. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  273. } else {
  274. $meta = $em->getClassMetadata(get_class($entity));
  275. $id = array();
  276. foreach ($meta->identifier as $name) {
  277. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  278. }
  279. }
  280. if ($single) {
  281. $id = current($id);
  282. }
  283. return $id;
  284. }
  285. }