Closure.php 11 KB

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