Closure.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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-dev') <= 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-dev') <= 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. protected function getJoinColumnFieldName($association)
  159. {
  160. if (count($association['joinColumnFieldNames']) > 1) {
  161. throw new RuntimeException('More association on field '.$association['fieldName']);
  162. }
  163. return array_shift($association['joinColumnFieldNames']);
  164. }
  165. /**
  166. * {@inheritdoc}
  167. */
  168. public function processPostPersist($em, $entity)
  169. {
  170. $uow = $em->getUnitOfWork();
  171. if ($uow->hasPendingInsertions()) {
  172. return;
  173. }
  174. while ($node = array_shift($this->pendingChildNodeInserts)) {
  175. $meta = $em->getClassMetadata(get_class($node));
  176. $config = $this->listener->getConfiguration($em, $meta->name);
  177. $identifier = $meta->getSingleIdentifierFieldName();
  178. $nodeId = $meta->getReflectionProperty($identifier)->getValue($node);
  179. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  180. $closureClass = $config['closure'];
  181. $closureMeta = $em->getClassMetadata($closureClass);
  182. $closureTable = $closureMeta->getTableName();
  183. $ancestorColumnName = $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('ancestor'));
  184. $descendantColumnName = $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('descendant'));
  185. $depthColumnName = $em->getClassMetadata($config['closure'])->getColumnName('depth');
  186. $entries = array(
  187. array(
  188. $ancestorColumnName => $nodeId,
  189. $descendantColumnName => $nodeId,
  190. $depthColumnName => 0
  191. )
  192. );
  193. if ($parent) {
  194. $dql = "SELECT c, a FROM {$closureMeta->name} c";
  195. $dql .= " JOIN c.ancestor a";
  196. $dql .= " WHERE c.descendant = :parent";
  197. $q = $em->createQuery($dql);
  198. $q->setParameters(compact('parent'));
  199. $ancestors = $q->getArrayResult();
  200. foreach ($ancestors as $ancestor) {
  201. $entries[] = array(
  202. $ancestorColumnName => $ancestor['ancestor']['id'],
  203. $descendantColumnName => $nodeId,
  204. $depthColumnName => $ancestor['depth'] + 1
  205. );
  206. }
  207. }
  208. foreach ($entries as $closure) {
  209. if (!$em->getConnection()->insert($closureTable, $closure)) {
  210. throw new RuntimeException('Failed to insert new Closure record');
  211. }
  212. }
  213. }
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. public function processScheduledUpdate($em, $node)
  219. {
  220. $meta = $em->getClassMetadata(get_class($node));
  221. $config = $this->listener->getConfiguration($em, $meta->name);
  222. $uow = $em->getUnitOfWork();
  223. $changeSet = $uow->getEntityChangeSet($node);
  224. if (array_key_exists($config['parent'], $changeSet)) {
  225. $this->updateNode($em, $node, $changeSet[$config['parent']][0]);
  226. }
  227. }
  228. /**
  229. * Update node and closures
  230. *
  231. * @param EntityManager $em
  232. * @param object $node
  233. * @param object $oldParent
  234. */
  235. public function updateNode(EntityManager $em, $node, $oldParent)
  236. {
  237. $meta = $em->getClassMetadata(get_class($node));
  238. $config = $this->listener->getConfiguration($em, $meta->name);
  239. $closureMeta = $em->getClassMetadata($config['closure']);
  240. $nodeId = $this->extractIdentifier($em, $node);
  241. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  242. $table = $closureMeta->getTableName();
  243. $conn = $em->getConnection();
  244. // ensure integrity
  245. if ($parent) {
  246. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  247. $dql .= " WHERE c.ancestor = :node";
  248. $dql .= " AND c.descendant = :parent";
  249. $q = $em->createQuery($dql);
  250. $q->setParameters(compact('node', 'parent'));
  251. if ($q->getSingleScalarResult()) {
  252. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  253. }
  254. }
  255. if ($oldParent) {
  256. $subQuery = "SELECT c2.id FROM {$table} c1";
  257. $subQuery .= " JOIN {$table} c2 ON c1.descendant = c2.descendant";
  258. $subQuery .= " WHERE c1.ancestor = :nodeId AND c2.depth > c1.depth";
  259. $ids = $conn->fetchAll($subQuery, compact('nodeId'));
  260. if ($ids) {
  261. $ids = array_map(function($el) {
  262. return $el['id'];
  263. }, $ids);
  264. }
  265. // using subquery directly, sqlite acts unfriendly
  266. $query = "DELETE FROM {$table} WHERE id IN (".implode(', ', $ids).")";
  267. if (!$conn->executeQuery($query)) {
  268. throw new RuntimeException('Failed to remove old closures');
  269. }
  270. }
  271. if ($parent) {
  272. $parentId = $this->extractIdentifier($em, $parent);
  273. $query = "SELECT c1.ancestor, c2.descendant, (c1.depth + c2.depth + 1) AS depth";
  274. $query .= " FROM {$table} c1, {$table} c2";
  275. $query .= " WHERE c1.descendant = :parentId";
  276. $query .= " AND c2.ancestor = :nodeId";
  277. $closures = $conn->fetchAll($query, compact('nodeId', 'parentId'));
  278. foreach ($closures as $closure) {
  279. if (!$conn->insert($table, $closure)) {
  280. throw new RuntimeException('Failed to insert new Closure record');
  281. }
  282. }
  283. }
  284. }
  285. /**
  286. * Extracts identifiers from object or proxy
  287. *
  288. * @param EntityManager $em
  289. * @param object $entity
  290. * @param bool $single
  291. * @return mixed - array or single identifier
  292. */
  293. private function extractIdentifier(EntityManager $em, $entity, $single = true)
  294. {
  295. if ($entity instanceof Proxy) {
  296. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  297. } else {
  298. $meta = $em->getClassMetadata(get_class($entity));
  299. $id = array();
  300. foreach ($meta->identifier as $name) {
  301. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  302. }
  303. }
  304. if ($single) {
  305. $id = current($id);
  306. }
  307. return $id;
  308. }
  309. }