Closure.php 11 KB

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