Closure.php 12 KB

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