Closure.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. use Doctrine\ORM\Mapping\ClassMetadata;
  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. * @param \Doctrine\ORM\Mapping\ClassMetadata $meta
  276. * @param array $config
  277. */
  278. protected function setLevelFieldOnPendingNodes(ObjectManager $em)
  279. {
  280. if (!empty($this->pendingNodesLevelProcess)) {
  281. $first = array_slice($this->pendingNodesLevelProcess, 0, 1);
  282. $meta = $em->getClassMetadata(get_class($first[0]));
  283. unset($first);
  284. $config = $this->listener->getConfiguration($em, $meta->name);
  285. $closureClass = $config['closure'];
  286. $closureMeta = $em->getClassMetadata($closureClass);
  287. $uow = $em->getUnitOfWork();
  288. foreach ($this->pendingNodesLevelProcess as $node) {
  289. $children = $em->getRepository($meta->name)->children($node);
  290. foreach ($children as $child) {
  291. $this->pendingNodesLevelProcess[AbstractWrapper::wrap($child, $em)->getIdentifier()] = $child;
  292. }
  293. }
  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 ('.implode(', ', array_keys($this->pendingNodesLevelProcess)).') ';
  298. $sql .= 'GROUP BY c.descendant';
  299. $levels = $em->getConnection()->executeQuery($sql)->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. }