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