Closure.php 16 KB

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