Closure.php 16 KB

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