Closure.php 16 KB

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