AbstractMaterializedPath.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. namespace Gedmo\Tree\Strategy;
  3. use Gedmo\Tree\Strategy;
  4. use Doctrine\ORM\EntityManager;
  5. use Gedmo\Tree\TreeListener;
  6. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  7. use Doctrine\ORM\Query;
  8. use Doctrine\Common\Persistence\ObjectManager;
  9. use Gedmo\Mapping\Event\AdapterInterface;
  10. use Gedmo\Exception\RuntimeException;
  11. use Gedmo\Exception\TreeLockingException;
  12. /**
  13. * This strategy makes tree using materialized path strategy
  14. *
  15. * @author Gustavo Falco <comfortablynumb84@gmail.com>
  16. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  17. * @author <rocco@roccosportal.com>
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. abstract class AbstractMaterializedPath implements Strategy
  21. {
  22. const ACTION_INSERT = 'insert';
  23. const ACTION_UPDATE = 'update';
  24. const ACTION_REMOVE = 'remove';
  25. /**
  26. * TreeListener
  27. *
  28. * @var AbstractTreeListener
  29. */
  30. protected $listener = null;
  31. /**
  32. * Array of objects which were scheduled for path processes
  33. *
  34. * @var array
  35. */
  36. protected $scheduledForPathProcess = array();
  37. /**
  38. * Array of objects which were scheduled for path process.
  39. * This time, this array contains the objects with their ID
  40. * already set
  41. *
  42. * @var array
  43. */
  44. protected $scheduledForPathProcessWithIdSet = array();
  45. /**
  46. * Roots of trees which needs to be locked
  47. *
  48. * @var array
  49. */
  50. protected $rootsOfTreesWhichNeedsLocking = array();
  51. /**
  52. * Objects which are going to be inserted (set only if tree locking is used)
  53. *
  54. * @var array
  55. */
  56. protected $pendingObjectsToInsert = array();
  57. /**
  58. * Objects which are going to be updated (set only if tree locking is used)
  59. *
  60. * @var array
  61. */
  62. protected $pendingObjectsToUpdate = array();
  63. /**
  64. * Objects which are going to be removed (set only if tree locking is used)
  65. *
  66. * @var array
  67. */
  68. protected $pendingObjectsToRemove = array();
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function __construct(TreeListener $listener)
  73. {
  74. $this->listener = $listener;
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function getName()
  80. {
  81. return Strategy::MATERIALIZED_PATH;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function processScheduledInsertion($om, $node, AdapterInterface $ea)
  87. {
  88. $meta = $om->getClassMetadata(get_class($node));
  89. $config = $this->listener->getConfiguration($om, $meta->name);
  90. $fieldMapping = $meta->getFieldMapping($config['path_source']);
  91. if ($meta->isIdentifier($config['path_source']) || $fieldMapping['type'] === 'string') {
  92. $this->scheduledForPathProcess[spl_object_hash($node)] = $node;
  93. } else {
  94. $this->updateNode($om, $node, $ea);
  95. }
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public function processScheduledUpdate($om, $node, AdapterInterface $ea)
  101. {
  102. $meta = $om->getClassMetadata(get_class($node));
  103. $config = $this->listener->getConfiguration($om, $meta->name);
  104. $uow = $om->getUnitOfWork();
  105. $changeSet = $ea->getObjectChangeSet($uow, $node);
  106. if (isset($changeSet[$config['parent']]) || isset($changeSet[$config['path_source']])) {
  107. if (isset($changeSet[$config['path']])) {
  108. $originalPath = $changeSet[$config['path']][0];
  109. } else {
  110. $pathProp = $meta->getReflectionProperty($config['path']);
  111. $pathProp->setAccessible(true);
  112. $originalPath = $pathProp->getValue($node);
  113. }
  114. $this->updateNode($om, $node, $ea);
  115. $this->updateChildren($om, $node, $ea, $originalPath);
  116. }
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function processPostPersist($om, $node, AdapterInterface $ea)
  122. {
  123. $oid = spl_object_hash($node);
  124. if ($this->scheduledForPathProcess && array_key_exists($oid, $this->scheduledForPathProcess)) {
  125. $this->scheduledForPathProcessWithIdSet[$oid] = $node;
  126. unset($this->scheduledForPathProcess[$oid]);
  127. if (empty($this->scheduledForPathProcess)) {
  128. foreach ($this->scheduledForPathProcessWithIdSet as $oid => $node) {
  129. $this->updateNode($om, $node, $ea);
  130. unset($this->scheduledForPathProcessWithIdSet[$oid]);
  131. }
  132. }
  133. }
  134. $this->processPostEventsActions($om, $ea, $node, self::ACTION_INSERT);
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function processPostUpdate($om, $node, AdapterInterface $ea)
  140. {
  141. $this->processPostEventsActions($om, $ea, $node, self::ACTION_UPDATE);
  142. }
  143. /**
  144. * {@inheritdoc}
  145. */
  146. public function processPostRemove($om, $node, AdapterInterface $ea)
  147. {
  148. $this->processPostEventsActions($om, $ea, $node, self::ACTION_REMOVE);
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function onFlushEnd($om, AdapterInterface $ea)
  154. {
  155. $this->lockTrees($om, $ea);
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function processPreRemove($om, $node)
  161. {
  162. $this->processPreLockingActions($om, $node, self::ACTION_REMOVE);
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. public function processPrePersist($om, $node)
  168. {
  169. $this->processPreLockingActions($om, $node, self::ACTION_INSERT);
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function processPreUpdate($om, $node)
  175. {
  176. $this->processPreLockingActions($om, $node, self::ACTION_UPDATE);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function processMetadataLoad($om, $meta)
  182. {}
  183. /**
  184. * {@inheritdoc}
  185. */
  186. public function processScheduledDelete($om, $node)
  187. {
  188. $meta = $om->getClassMetadata(get_class($node));
  189. $config = $this->listener->getConfiguration($om, $meta->name);
  190. $this->removeNode($om, $meta, $config, $node);
  191. }
  192. /**
  193. * Update the $node
  194. *
  195. * @param ObjectManager $om
  196. * @param object $node - target node
  197. * @param object $ea - event adapter
  198. * @return void
  199. */
  200. public function updateNode(ObjectManager $om, $node, AdapterInterface $ea)
  201. {
  202. $oid = spl_object_hash($node);
  203. $meta = $om->getClassMetadata(get_class($node));
  204. $config = $this->listener->getConfiguration($om, $meta->name);
  205. $uow = $om->getUnitOfWork();
  206. $parentProp = $meta->getReflectionProperty($config['parent']);
  207. $parentProp->setAccessible(true);
  208. $parent = $parentProp->getValue($node);
  209. $pathProp = $meta->getReflectionProperty($config['path']);
  210. $pathProp->setAccessible(true);
  211. $pathSourceProp = $meta->getReflectionProperty($config['path_source']);
  212. $pathSourceProp->setAccessible(true);
  213. $path = $pathSourceProp->getValue($node);
  214. // We need to avoid the presence of the path separator in the path source
  215. if (strpos($path, $config['path_separator']) !== false) {
  216. $msg = 'You can\'t use the Path separator ("%s") as a character for your PathSource field value.';
  217. throw new RuntimeException(sprintf($msg, $config['path_separator']));
  218. }
  219. $fieldMapping = $meta->getFieldMapping($config['path_source']);
  220. // default behavior: if PathSource field is a string, we append the ID to the path
  221. // path_append_id is true: always append id
  222. // path_append_id is false: never append id
  223. if ($config['path_append_id'] === true || ($fieldMapping['type'] === 'string' && $config['path_append_id']!==false)) {
  224. if (method_exists($meta, 'getIdentifierValue')) {
  225. $identifier = $meta->getIdentifierValue($node);
  226. } else {
  227. $identifierProp = $meta->getReflectionProperty($meta->getSingleIdentifierFieldName());
  228. $identifierProp->setAccessible(true);
  229. $identifier = $identifierProp->getValue($node);
  230. }
  231. $path .= '-'.$identifier;
  232. }
  233. if ($parent) {
  234. // Ensure parent has been initialized in the case where it's a proxy
  235. $om->initializeObject($parent);
  236. $changeSet = $uow->isScheduledForUpdate($parent) ? $ea->getObjectChangeSet($uow, $parent) : false;
  237. $pathOrPathSourceHasChanged = $changeSet && (isset($changeSet[$config['path_source']]) || isset($changeSet[$config['path']]));
  238. if ($pathOrPathSourceHasChanged || !$pathProp->getValue($parent)) {
  239. $this->updateNode($om, $parent, $ea);
  240. }
  241. $parentPath = $pathProp->getValue($parent);
  242. // if parent path not ends with separator
  243. if ($parentPath[strlen($parentPath) - 1] !== $config['path_separator']) {
  244. // add separator
  245. $path = $pathProp->getValue($parent) . $config['path_separator'] . $path;
  246. } else {
  247. // don't add separator
  248. $path = $pathProp->getValue($parent) . $path;
  249. }
  250. }
  251. if ($config['path_starts_with_separator'] && (strlen($path) > 0 && $path[0] !== $config['path_separator'])) {
  252. $path = $config['path_separator'] . $path;
  253. }
  254. if ($config['path_ends_with_separator'] && ($path[strlen($path) - 1] !== $config['path_separator'])) {
  255. $path .= $config['path_separator'];
  256. }
  257. $pathProp->setValue($node, $path);
  258. $changes = array(
  259. $config['path'] => array(null, $path)
  260. );
  261. if (isset($config['path_hash'])) {
  262. $pathHash = md5($path);
  263. $pathHashProp = $meta->getReflectionProperty($config['path_hash']);
  264. $pathHashProp->setAccessible(true);
  265. $pathHashProp->setValue($node, $pathHash);
  266. $changes[$config['path_hash']] = array(null, $pathHash);
  267. }
  268. if (isset($config['level'])) {
  269. $level = substr_count($path, $config['path_separator']);
  270. $levelProp = $meta->getReflectionProperty($config['level']);
  271. $levelProp->setAccessible(true);
  272. $levelProp->setValue($node, $level);
  273. $changes[$config['level']] = array(null, $level);
  274. }
  275. $uow->scheduleExtraUpdate($node, $changes);
  276. $ea->setOriginalObjectProperty($uow, $oid, $config['path'], $path);
  277. if(isset($config['path_hash'])){
  278. $ea->setOriginalObjectProperty($uow, $oid, $config['path_hash'], $pathHash);
  279. }
  280. }
  281. /**
  282. * Update node's children
  283. *
  284. * @param ObjectManager $om
  285. * @param object $node
  286. * @param AdapterInterface $ea
  287. * @param string $originalPath
  288. * @return void
  289. */
  290. public function updateChildren(ObjectManager $om, $node, AdapterInterface $ea, $originalPath)
  291. {
  292. $meta = $om->getClassMetadata(get_class($node));
  293. $config = $this->listener->getConfiguration($om, $meta->name);
  294. $children = $this->getChildren($om, $meta, $config, $originalPath);
  295. foreach ($children as $child) {
  296. $this->updateNode($om, $child, $ea);
  297. }
  298. }
  299. /**
  300. * Process pre-locking actions
  301. *
  302. * @param ObjectManager $om
  303. * @param object $node
  304. * @param string $action
  305. * @return void
  306. */
  307. public function processPreLockingActions($om, $node, $action)
  308. {
  309. $meta = $om->getClassMetadata(get_class($node));
  310. $config = $this->listener->getConfiguration($om, $meta->name);
  311. if ($config['activate_locking']) {;
  312. $parentProp = $meta->getReflectionProperty($config['parent']);
  313. $parentProp->setAccessible(true);
  314. $parentNode = $node;
  315. while (!is_null($parent = $parentProp->getValue($parentNode))) {
  316. $parentNode = $parent;
  317. }
  318. // In some cases, the parent could be a not initialized proxy. In this case, the
  319. // "lockTime" field may NOT be loaded yet and have null instead of the date.
  320. // We need to be sure that this field has its real value
  321. if ($parentNode !== $node && $parentNode instanceof \Doctrine\ODM\MongoDB\Proxy\Proxy) {
  322. $reflMethod = new \ReflectionMethod(get_class($parentNode), '__load');
  323. $reflMethod->setAccessible(true);
  324. $reflMethod->invoke($parentNode);
  325. }
  326. // If tree is already locked, we throw an exception
  327. $lockTimeProp = $meta->getReflectionProperty($config['lock_time']);
  328. $lockTimeProp->setAccessible(true);
  329. $lockTime = $lockTimeProp->getValue($parentNode);
  330. if (!is_null($lockTime)) {
  331. $lockTime = $lockTime instanceof \MongoDate ? $lockTime->sec : $lockTime->getTimestamp();
  332. }
  333. if (!is_null($lockTime) && ($lockTime >= (time() - $config['locking_timeout']))) {
  334. $msg = 'Tree with root id "%s" is locked.';
  335. $id = $meta->getIdentifierValue($parentNode);
  336. throw new TreeLockingException(sprintf($msg, $id));
  337. }
  338. $this->rootsOfTreesWhichNeedsLocking[spl_object_hash($parentNode)] = $parentNode;
  339. $oid = spl_object_hash($node);
  340. switch ($action) {
  341. case self::ACTION_INSERT:
  342. $this->pendingObjectsToInsert[$oid] = $node;
  343. break;
  344. case self::ACTION_UPDATE:
  345. $this->pendingObjectsToUpdate[$oid] = $node;
  346. break;
  347. case self::ACTION_REMOVE:
  348. $this->pendingObjectsToRemove[$oid] = $node;
  349. break;
  350. default:
  351. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  352. }
  353. }
  354. }
  355. /**
  356. * Process pre-locking actions
  357. *
  358. * @param ObjectManager $om
  359. * @param AdapterInterface $ea
  360. * @param object $node
  361. * @param string $action
  362. * @return void
  363. */
  364. public function processPostEventsActions(ObjectManager $om, AdapterInterface $ea, $node, $action)
  365. {
  366. $meta = $om->getClassMetadata(get_class($node));
  367. $config = $this->listener->getConfiguration($om, $meta->name);
  368. if ($config['activate_locking']) {
  369. switch ($action) {
  370. case self::ACTION_INSERT:
  371. unset($this->pendingObjectsToInsert[spl_object_hash($node)]);
  372. break;
  373. case self::ACTION_UPDATE:
  374. unset($this->pendingObjectsToUpdate[spl_object_hash($node)]);
  375. break;
  376. case self::ACTION_REMOVE:
  377. unset($this->pendingObjectsToRemove[spl_object_hash($node)]);
  378. break;
  379. default:
  380. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  381. }
  382. if (empty($this->pendingObjectsToInsert) && empty($this->pendingObjectsToUpdate) &&
  383. empty($this->pendingObjectsToRemove)) {
  384. $this->releaseTreeLocks($om, $ea);
  385. }
  386. }
  387. }
  388. /**
  389. * Locks all needed trees
  390. *
  391. * @param ObjectManager $om
  392. * @param AdapterInterface $ea
  393. * @return void
  394. */
  395. protected function lockTrees(ObjectManager $om, AdapterInterface $ea)
  396. {
  397. // Do nothing by default
  398. }
  399. /**
  400. * Releases all trees which are locked
  401. *
  402. * @param ObjectManager $om
  403. * @param AdapterInterface $ea
  404. * @return void
  405. */
  406. protected function releaseTreeLocks(ObjectManager $om, AdapterInterface $ea)
  407. {
  408. // Do nothing by default
  409. }
  410. /**
  411. * Remove node and its children
  412. *
  413. * @param ObjectManager $om
  414. * @param object $meta - Metadata
  415. * @param object $config - config
  416. * @param object $node - node to remove
  417. * @return void
  418. */
  419. abstract public function removeNode($om, $meta, $config, $node);
  420. /**
  421. * Returns children of the node with its original path
  422. *
  423. * @param ObjectManager $om
  424. * @param object $meta - Metadata
  425. * @param object $config - config
  426. * @param string $originalPath - original path of object
  427. * @return Doctrine\ODM\MongoDB\Cursor
  428. */
  429. abstract public function getChildren($om, $meta, $config, $originalPath);
  430. }