Closure.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\ORM\Version;
  5. use Doctrine\ORM\Proxy\Proxy;
  6. use Doctrine\ORM\EntityManager;
  7. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  8. use Doctrine\Common\Persistence\ObjectManager;
  9. use Gedmo\Tree\Strategy;
  10. use Gedmo\Tree\TreeListener;
  11. use Gedmo\Tool\Wrapper\AbstractWrapper;
  12. use Gedmo\Exception\RuntimeException;
  13. use Gedmo\Mapping\Event\AdapterInterface;
  14. /**
  15. * This strategy makes tree act like
  16. * a closure table.
  17. *
  18. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  19. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  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. * List of nodes which has their parents updated, but using
  40. * new nodes. They have to wait until their parents are inserted
  41. * on DB to make the update
  42. *
  43. * @var array
  44. */
  45. private $pendingNodeUpdates = array();
  46. /**
  47. * List of pending Nodes, which needs their "level"
  48. * field value set
  49. *
  50. * @var array
  51. */
  52. private $pendingNodesLevelProcess = array();
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function __construct(TreeListener $listener)
  57. {
  58. $this->listener = $listener;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function getName()
  64. {
  65. return Strategy::CLOSURE;
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function processMetadataLoad($em, $meta)
  71. {
  72. $config = $this->listener->getConfiguration($em, $meta->name);
  73. $closureMetadata = $em->getClassMetadata($config['closure']);
  74. $cmf = $em->getMetadataFactory();
  75. if (!$closureMetadata->hasAssociation('ancestor')) {
  76. // create ancestor mapping
  77. $ancestorMapping = array(
  78. 'fieldName' => 'ancestor',
  79. 'id' => false,
  80. 'joinColumns' => array(
  81. array(
  82. 'name' => 'ancestor',
  83. 'referencedColumnName' => 'id',
  84. 'unique' => false,
  85. 'nullable' => false,
  86. 'onDelete' => 'CASCADE',
  87. 'onUpdate' => null,
  88. 'columnDefinition' => null,
  89. )
  90. ),
  91. 'inversedBy' => null,
  92. 'targetEntity' => $meta->name,
  93. 'cascade' => null,
  94. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  95. );
  96. $closureMetadata->mapManyToOne($ancestorMapping);
  97. if (Version::compare('2.3.0-dev') <= 0) {
  98. $closureMetadata->reflFields['ancestor'] = $cmf
  99. ->getReflectionService()
  100. ->getAccessibleProperty($closureMetadata->name, 'ancestor')
  101. ;
  102. }
  103. }
  104. if (!$closureMetadata->hasAssociation('descendant')) {
  105. // create descendant mapping
  106. $descendantMapping = array(
  107. 'fieldName' => 'descendant',
  108. 'id' => false,
  109. 'joinColumns' => array(
  110. array(
  111. 'name' => 'descendant',
  112. 'referencedColumnName' => 'id',
  113. 'unique' => false,
  114. 'nullable' => false,
  115. 'onDelete' => 'CASCADE',
  116. 'onUpdate' => null,
  117. 'columnDefinition' => null,
  118. )
  119. ),
  120. 'inversedBy' => null,
  121. 'targetEntity' => $meta->name,
  122. 'cascade' => null,
  123. 'fetch' => ClassMetadataInfo::FETCH_LAZY
  124. );
  125. $closureMetadata->mapManyToOne($descendantMapping);
  126. if (Version::compare('2.3.0-dev') <= 0) {
  127. $closureMetadata->reflFields['descendant'] = $cmf
  128. ->getReflectionService()
  129. ->getAccessibleProperty($closureMetadata->name, 'descendant')
  130. ;
  131. }
  132. }
  133. // create unique index on ancestor and descendant
  134. $indexName = substr(strtoupper("IDX_" . md5($closureMetadata->name)), 0, 20);
  135. $closureMetadata->table['uniqueConstraints'][$indexName] = array(
  136. 'columns' => array(
  137. $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('ancestor')),
  138. $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('descendant'))
  139. )
  140. );
  141. // this one may not be very usefull
  142. $indexName = substr(strtoupper("IDX_" . md5($meta->name . 'depth')), 0, 20);
  143. $closureMetadata->table['indexes'][$indexName] = array(
  144. 'columns' => array('depth')
  145. );
  146. if ($cacheDriver = $cmf->getCacheDriver()) {
  147. $cacheDriver->save($closureMetadata->name."\$CLASSMETADATA", $closureMetadata, null);
  148. }
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function onFlushEnd($em, AdapterInterface $ea)
  154. {}
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function processPrePersist($em, $node)
  159. {
  160. $this->pendingChildNodeInserts[spl_object_hash($node)] = $node;
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function processPreUpdate($em, $node)
  166. {}
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function processPreRemove($em, $node)
  171. {}
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function processScheduledInsertion($em, $node, AdapterInterface $ea)
  176. {}
  177. /**
  178. * {@inheritdoc}
  179. */
  180. public function processScheduledDelete($em, $entity)
  181. {}
  182. protected function getJoinColumnFieldName($association)
  183. {
  184. if (count($association['joinColumnFieldNames']) > 1) {
  185. throw new RuntimeException('More association on field '.$association['fieldName']);
  186. }
  187. return array_shift($association['joinColumnFieldNames']);
  188. }
  189. /**
  190. * {@inheritdoc}
  191. */
  192. public function processPostUpdate($em, $entity, AdapterInterface $ea)
  193. {
  194. $meta = $em->getClassMetadata(get_class($entity));
  195. $config = $this->listener->getConfiguration($em, $meta->name);
  196. // Process TreeLevel field value
  197. if (!empty($config)) {
  198. $this->setLevelFieldOnPendingNodes($em);
  199. }
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function processPostRemove($em, $entity, AdapterInterface $ea)
  205. {}
  206. /**
  207. * {@inheritdoc}
  208. */
  209. public function processPostPersist($em, $entity, AdapterInterface $ea)
  210. {
  211. $uow = $em->getUnitOfWork();
  212. while ($node = array_shift($this->pendingChildNodeInserts)) {
  213. $meta = $em->getClassMetadata(get_class($node));
  214. $config = $this->listener->getConfiguration($em, $meta->name);
  215. $identifier = $meta->getSingleIdentifierFieldName();
  216. $nodeId = $meta->getReflectionProperty($identifier)->getValue($node);
  217. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  218. $closureClass = $config['closure'];
  219. $closureMeta = $em->getClassMetadata($closureClass);
  220. $closureTable = $closureMeta->getTableName();
  221. $ancestorColumnName = $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('ancestor'));
  222. $descendantColumnName = $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('descendant'));
  223. $depthColumnName = $em->getClassMetadata($config['closure'])->getColumnName('depth');
  224. $entries = array(
  225. array(
  226. $ancestorColumnName => $nodeId,
  227. $descendantColumnName => $nodeId,
  228. $depthColumnName => 0
  229. )
  230. );
  231. if ($parent) {
  232. $dql = "SELECT c, a FROM {$closureMeta->name} c";
  233. $dql .= " JOIN c.ancestor a";
  234. $dql .= " WHERE c.descendant = :parent";
  235. $q = $em->createQuery($dql);
  236. $q->setParameters(compact('parent'));
  237. $ancestors = $q->getArrayResult();
  238. foreach ($ancestors as $ancestor) {
  239. $entries[] = array(
  240. $ancestorColumnName => $ancestor['ancestor']['id'],
  241. $descendantColumnName => $nodeId,
  242. $depthColumnName => $ancestor['depth'] + 1
  243. );
  244. }
  245. if (isset($config['level'])) {
  246. $this->pendingNodesLevelProcess[$nodeId] = $node;
  247. }
  248. } else if (isset($config['level'])) {
  249. $uow->scheduleExtraUpdate($node, array($config['level'] => array(null, 1)));
  250. $ea->setOriginalObjectProperty($uow, spl_object_hash($node), $config['level'], 1);
  251. }
  252. foreach ($entries as $closure) {
  253. if (!$em->getConnection()->insert($closureTable, $closure)) {
  254. throw new RuntimeException('Failed to insert new Closure record');
  255. }
  256. }
  257. }
  258. // Process pending node updates
  259. if (!empty($this->pendingNodeUpdates)) {
  260. foreach ($this->pendingNodeUpdates as $info) {
  261. $this->updateNode($em, $info['node'], $info['oldParent']);
  262. }
  263. $this->pendingNodeUpdates = array();
  264. }
  265. // Process TreeLevel field value
  266. $this->setLevelFieldOnPendingNodes($em);
  267. }
  268. /**
  269. * Process pending entities to set their "level" value
  270. *
  271. * @param \Doctrine\Common\Persistence\ObjectManager $em
  272. */
  273. protected function setLevelFieldOnPendingNodes(ObjectManager $em)
  274. {
  275. if (!empty($this->pendingNodesLevelProcess)) {
  276. $first = array_slice($this->pendingNodesLevelProcess, 0, 1);
  277. $first = array_shift($first);
  278. $meta = $em->getClassMetadata(get_class($first));
  279. unset($first);
  280. $identifier = $meta->getIdentifier();
  281. $mapping = $meta->getFieldMapping($identifier[0]);
  282. $config = $this->listener->getConfiguration($em, $meta->name);
  283. $closureClass = $config['closure'];
  284. $closureMeta = $em->getClassMetadata($closureClass);
  285. $uow = $em->getUnitOfWork();
  286. foreach ($this->pendingNodesLevelProcess as $node) {
  287. $children = $em->getRepository($meta->name)->children($node);
  288. foreach ($children as $child) {
  289. $this->pendingNodesLevelProcess[AbstractWrapper::wrap($child, $em)->getIdentifier()] = $child;
  290. }
  291. }
  292. // Avoid type conversion performance penalty
  293. $type = 'integer' === $mapping['type'] ? Connection::PARAM_INT_ARRAY : Connection::PARAM_STR_ARRAY;
  294. // We calculate levels for all nodes
  295. $sql = 'SELECT c.descendant, MAX(c.depth) + 1 AS level ';
  296. $sql .= 'FROM '.$closureMeta->getTableName().' c ';
  297. $sql .= 'WHERE c.descendant IN (?) ';
  298. $sql .= 'GROUP BY c.descendant';
  299. $levels = $em->getConnection()->executeQuery($sql, array(array_keys($this->pendingNodesLevelProcess)), array($type))->fetchAll(\PDO::FETCH_KEY_PAIR);
  300. // Now we update levels
  301. foreach ($this->pendingNodesLevelProcess as $nodeId => $node) {
  302. // Update new level
  303. $level = $levels[$nodeId];
  304. $uow->scheduleExtraUpdate(
  305. $node,
  306. array($config['level'] => array(
  307. $meta->getReflectionProperty($config['level'])->getValue($node), $level
  308. ))
  309. );
  310. $uow->setOriginalEntityProperty(spl_object_hash($node), $config['level'], $level);
  311. }
  312. $this->pendingNodesLevelProcess = array();
  313. }
  314. }
  315. /**
  316. * {@inheritdoc}
  317. */
  318. public function processScheduledUpdate($em, $node, AdapterInterface $ea)
  319. {
  320. $meta = $em->getClassMetadata(get_class($node));
  321. $config = $this->listener->getConfiguration($em, $meta->name);
  322. $uow = $em->getUnitOfWork();
  323. $changeSet = $uow->getEntityChangeSet($node);
  324. if (array_key_exists($config['parent'], $changeSet)) {
  325. // If new parent is new, we need to delay the update of the node
  326. // until it is inserted on DB
  327. $parent = $changeSet[$config['parent']][1] ? AbstractWrapper::wrap($changeSet[$config['parent']][1], $em) : null;
  328. if ($parent && !$parent->getIdentifier()) {
  329. $this->pendingNodeUpdates[spl_object_hash($node)] = array(
  330. 'node' => $node,
  331. 'oldParent' => $changeSet[$config['parent']][0]
  332. );
  333. } else {
  334. $this->updateNode($em, $node, $changeSet[$config['parent']][0]);
  335. }
  336. }
  337. }
  338. /**
  339. * Update node and closures
  340. *
  341. * @param EntityManager $em
  342. * @param object $node
  343. * @param object $oldParent
  344. */
  345. public function updateNode(EntityManager $em, $node, $oldParent)
  346. {
  347. $wrapped = AbstractWrapper::wrap($node, $em);
  348. $meta = $wrapped->getMetadata();
  349. $config = $this->listener->getConfiguration($em, $meta->name);
  350. $closureMeta = $em->getClassMetadata($config['closure']);
  351. $nodeId = $wrapped->getIdentifier();
  352. $parent = $wrapped->getPropertyValue($config['parent']);
  353. $table = $closureMeta->getTableName();
  354. $conn = $em->getConnection();
  355. // ensure integrity
  356. if ($parent) {
  357. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  358. $dql .= " WHERE c.ancestor = :node";
  359. $dql .= " AND c.descendant = :parent";
  360. $q = $em->createQuery($dql);
  361. $q->setParameters(compact('node', 'parent'));
  362. if ($q->getSingleScalarResult()) {
  363. throw new \Gedmo\Exception\UnexpectedValueException("Cannot set child as parent to node: {$nodeId}");
  364. }
  365. }
  366. if ($oldParent) {
  367. $subQuery = "SELECT c2.id FROM {$table} c1";
  368. $subQuery .= " JOIN {$table} c2 ON c1.descendant = c2.descendant";
  369. $subQuery .= " WHERE c1.ancestor = :nodeId AND c2.depth > c1.depth";
  370. $ids = $conn->fetchAll($subQuery, compact('nodeId'));
  371. if ($ids) {
  372. $ids = array_map(function($el) {
  373. return $el['id'];
  374. }, $ids);
  375. }
  376. // using subquery directly, sqlite acts unfriendly
  377. $query = "DELETE FROM {$table} WHERE id IN (".implode(', ', $ids).")";
  378. if (!$conn->executeQuery($query)) {
  379. throw new RuntimeException('Failed to remove old closures');
  380. }
  381. }
  382. if ($parent) {
  383. $wrappedParent = AbstractWrapper::wrap($parent, $em);
  384. $parentId = $wrappedParent->getIdentifier();
  385. $query = "SELECT c1.ancestor, c2.descendant, (c1.depth + c2.depth + 1) AS depth";
  386. $query .= " FROM {$table} c1, {$table} c2";
  387. $query .= " WHERE c1.descendant = :parentId";
  388. $query .= " AND c2.ancestor = :nodeId";
  389. $closures = $conn->fetchAll($query, compact('nodeId', 'parentId'));
  390. foreach ($closures as $closure) {
  391. if (!$conn->insert($table, $closure)) {
  392. throw new RuntimeException('Failed to insert new Closure record');
  393. }
  394. }
  395. }
  396. if (isset($config['level'])) {
  397. $this->pendingNodesLevelProcess[$nodeId] = $node;
  398. }
  399. }
  400. }