AbstractMaterializedPath.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. <?php
  2. namespace Gedmo\Tree\Strategy;
  3. use Gedmo\Tree\Strategy;
  4. use Gedmo\Tree\TreeListener;
  5. use Doctrine\Common\Persistence\ObjectManager;
  6. use Doctrine\ODM\MongoDB\UnitOfWork as MongoDBUnitOfWork;
  7. use Gedmo\Mapping\Event\AdapterInterface;
  8. use Gedmo\Exception\RuntimeException;
  9. use Gedmo\Exception\TreeLockingException;
  10. /**
  11. * This strategy makes tree using materialized path strategy
  12. *
  13. * @author Gustavo Falco <comfortablynumb84@gmail.com>
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @author <rocco@roccosportal.com>
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. abstract class AbstractMaterializedPath implements Strategy
  19. {
  20. const ACTION_INSERT = 'insert';
  21. const ACTION_UPDATE = 'update';
  22. const ACTION_REMOVE = 'remove';
  23. /**
  24. * TreeListener
  25. *
  26. * @var AbstractTreeListener
  27. */
  28. protected $listener = null;
  29. /**
  30. * Array of objects which were scheduled for path processes
  31. *
  32. * @var array
  33. */
  34. protected $scheduledForPathProcess = array();
  35. /**
  36. * Array of objects which were scheduled for path process.
  37. * This time, this array contains the objects with their ID
  38. * already set
  39. *
  40. * @var array
  41. */
  42. protected $scheduledForPathProcessWithIdSet = array();
  43. /**
  44. * Roots of trees which needs to be locked
  45. *
  46. * @var array
  47. */
  48. protected $rootsOfTreesWhichNeedsLocking = array();
  49. /**
  50. * Objects which are going to be inserted (set only if tree locking is used)
  51. *
  52. * @var array
  53. */
  54. protected $pendingObjectsToInsert = array();
  55. /**
  56. * Objects which are going to be updated (set only if tree locking is used)
  57. *
  58. * @var array
  59. */
  60. protected $pendingObjectsToUpdate = array();
  61. /**
  62. * Objects which are going to be removed (set only if tree locking is used)
  63. *
  64. * @var array
  65. */
  66. protected $pendingObjectsToRemove = array();
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function __construct(TreeListener $listener)
  71. {
  72. $this->listener = $listener;
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function getName()
  78. {
  79. return Strategy::MATERIALIZED_PATH;
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function processScheduledInsertion($om, $node, AdapterInterface $ea)
  85. {
  86. $meta = $om->getClassMetadata(get_class($node));
  87. $config = $this->listener->getConfiguration($om, $meta->name);
  88. $fieldMapping = $meta->getFieldMapping($config['path_source']);
  89. if ($meta->isIdentifier($config['path_source']) || $fieldMapping['type'] === 'string') {
  90. $this->scheduledForPathProcess[spl_object_hash($node)] = $node;
  91. } else {
  92. $this->updateNode($om, $node, $ea);
  93. }
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function processScheduledUpdate($om, $node, AdapterInterface $ea)
  99. {
  100. $meta = $om->getClassMetadata(get_class($node));
  101. $config = $this->listener->getConfiguration($om, $meta->name);
  102. $uow = $om->getUnitOfWork();
  103. $changeSet = $ea->getObjectChangeSet($uow, $node);
  104. if (isset($changeSet[$config['parent']]) || isset($changeSet[$config['path_source']])) {
  105. if (isset($changeSet[$config['path']])) {
  106. $originalPath = $changeSet[$config['path']][0];
  107. } else {
  108. $pathProp = $meta->getReflectionProperty($config['path']);
  109. $pathProp->setAccessible(true);
  110. $originalPath = $pathProp->getValue($node);
  111. }
  112. $this->updateNode($om, $node, $ea);
  113. $this->updateChildren($om, $node, $ea, $originalPath);
  114. }
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. public function processPostPersist($om, $node, AdapterInterface $ea)
  120. {
  121. $oid = spl_object_hash($node);
  122. if ($this->scheduledForPathProcess && array_key_exists($oid, $this->scheduledForPathProcess)) {
  123. $this->scheduledForPathProcessWithIdSet[$oid] = $node;
  124. unset($this->scheduledForPathProcess[$oid]);
  125. if (empty($this->scheduledForPathProcess)) {
  126. foreach ($this->scheduledForPathProcessWithIdSet as $oid => $node) {
  127. $this->updateNode($om, $node, $ea);
  128. unset($this->scheduledForPathProcessWithIdSet[$oid]);
  129. }
  130. }
  131. }
  132. $this->processPostEventsActions($om, $ea, $node, self::ACTION_INSERT);
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function processPostUpdate($om, $node, AdapterInterface $ea)
  138. {
  139. $this->processPostEventsActions($om, $ea, $node, self::ACTION_UPDATE);
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function processPostRemove($om, $node, AdapterInterface $ea)
  145. {
  146. $this->processPostEventsActions($om, $ea, $node, self::ACTION_REMOVE);
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. public function onFlushEnd($om, AdapterInterface $ea)
  152. {
  153. $this->lockTrees($om, $ea);
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function processPreRemove($om, $node)
  159. {
  160. $this->processPreLockingActions($om, $node, self::ACTION_REMOVE);
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function processPrePersist($om, $node)
  166. {
  167. $this->processPreLockingActions($om, $node, self::ACTION_INSERT);
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function processPreUpdate($om, $node)
  173. {
  174. $this->processPreLockingActions($om, $node, self::ACTION_UPDATE);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function processMetadataLoad($om, $meta)
  180. {
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function processScheduledDelete($om, $node)
  186. {
  187. $meta = $om->getClassMetadata(get_class($node));
  188. $config = $this->listener->getConfiguration($om, $meta->name);
  189. $this->removeNode($om, $meta, $config, $node);
  190. }
  191. /**
  192. * Update the $node
  193. *
  194. * @param ObjectManager $om
  195. * @param object $node - target node
  196. * @param AdapterInterface $ea - event adapter
  197. *
  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['root'])) {
  269. $root = null;
  270. // Define the root value by grabbing the top of the current path
  271. $rootFinderPath = explode($config['path_separator'], $path);
  272. $rootIndex = $config['path_starts_with_separator'] ? 1 : 0;
  273. $root = $rootFinderPath[$rootIndex];
  274. // If it is an association, then make it an reference
  275. // to the entity
  276. if ($meta->hasAssociation($config['root'])) {
  277. $rootClass = $meta->getAssociationTargetClass($config['root']);
  278. $root = $om->getReference($rootClass, $root);
  279. }
  280. $rootProp = $meta->getReflectionProperty($config['root']);
  281. $rootProp->setAccessible(true);
  282. $rootProp->setValue($node, $root);
  283. $changes[$config['root']] = array(null, $root);
  284. }
  285. if (isset($config['level'])) {
  286. $level = substr_count($path, $config['path_separator']);
  287. $levelProp = $meta->getReflectionProperty($config['level']);
  288. $levelProp->setAccessible(true);
  289. $levelProp->setValue($node, $level);
  290. $changes[$config['level']] = array(null, $level);
  291. }
  292. if (!$uow instanceof MongoDBUnitOfWork) {
  293. $ea->setOriginalObjectProperty($uow, $oid, $config['path'], $path);
  294. $uow->scheduleExtraUpdate($node, $changes);
  295. } else {
  296. $ea->recomputeSingleObjectChangeSet($uow, $meta, $node);
  297. }
  298. if (isset($config['path_hash'])) {
  299. $ea->setOriginalObjectProperty($uow, $oid, $config['path_hash'], $pathHash);
  300. }
  301. }
  302. /**
  303. * Update node's children
  304. *
  305. * @param ObjectManager $om
  306. * @param object $node
  307. * @param AdapterInterface $ea
  308. * @param string $originalPath
  309. *
  310. * @return void
  311. */
  312. public function updateChildren(ObjectManager $om, $node, AdapterInterface $ea, $originalPath)
  313. {
  314. $meta = $om->getClassMetadata(get_class($node));
  315. $config = $this->listener->getConfiguration($om, $meta->name);
  316. $children = $this->getChildren($om, $meta, $config, $originalPath);
  317. foreach ($children as $child) {
  318. $this->updateNode($om, $child, $ea);
  319. }
  320. }
  321. /**
  322. * Process pre-locking actions
  323. *
  324. * @param ObjectManager $om
  325. * @param object $node
  326. * @param string $action
  327. *
  328. * @return void
  329. */
  330. public function processPreLockingActions($om, $node, $action)
  331. {
  332. $meta = $om->getClassMetadata(get_class($node));
  333. $config = $this->listener->getConfiguration($om, $meta->name);
  334. if ($config['activate_locking']) {
  335. ;
  336. $parentProp = $meta->getReflectionProperty($config['parent']);
  337. $parentProp->setAccessible(true);
  338. $parentNode = $node;
  339. while (!is_null($parent = $parentProp->getValue($parentNode))) {
  340. $parentNode = $parent;
  341. }
  342. // In some cases, the parent could be a not initialized proxy. In this case, the
  343. // "lockTime" field may NOT be loaded yet and have null instead of the date.
  344. // We need to be sure that this field has its real value
  345. if ($parentNode !== $node && $parentNode instanceof \Doctrine\ODM\MongoDB\Proxy\Proxy) {
  346. $reflMethod = new \ReflectionMethod(get_class($parentNode), '__load');
  347. $reflMethod->setAccessible(true);
  348. $reflMethod->invoke($parentNode);
  349. }
  350. // If tree is already locked, we throw an exception
  351. $lockTimeProp = $meta->getReflectionProperty($config['lock_time']);
  352. $lockTimeProp->setAccessible(true);
  353. $lockTime = $lockTimeProp->getValue($parentNode);
  354. if (!is_null($lockTime)) {
  355. $lockTime = $lockTime instanceof \MongoDate ? $lockTime->sec : $lockTime->getTimestamp();
  356. }
  357. if (!is_null($lockTime) && ($lockTime >= (time() - $config['locking_timeout']))) {
  358. $msg = 'Tree with root id "%s" is locked.';
  359. $id = $meta->getIdentifierValue($parentNode);
  360. throw new TreeLockingException(sprintf($msg, $id));
  361. }
  362. $this->rootsOfTreesWhichNeedsLocking[spl_object_hash($parentNode)] = $parentNode;
  363. $oid = spl_object_hash($node);
  364. switch ($action) {
  365. case self::ACTION_INSERT:
  366. $this->pendingObjectsToInsert[$oid] = $node;
  367. break;
  368. case self::ACTION_UPDATE:
  369. $this->pendingObjectsToUpdate[$oid] = $node;
  370. break;
  371. case self::ACTION_REMOVE:
  372. $this->pendingObjectsToRemove[$oid] = $node;
  373. break;
  374. default:
  375. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  376. }
  377. }
  378. }
  379. /**
  380. * Process pre-locking actions
  381. *
  382. * @param ObjectManager $om
  383. * @param AdapterInterface $ea
  384. * @param object $node
  385. * @param string $action
  386. *
  387. * @return void
  388. */
  389. public function processPostEventsActions(ObjectManager $om, AdapterInterface $ea, $node, $action)
  390. {
  391. $meta = $om->getClassMetadata(get_class($node));
  392. $config = $this->listener->getConfiguration($om, $meta->name);
  393. if ($config['activate_locking']) {
  394. switch ($action) {
  395. case self::ACTION_INSERT:
  396. unset($this->pendingObjectsToInsert[spl_object_hash($node)]);
  397. break;
  398. case self::ACTION_UPDATE:
  399. unset($this->pendingObjectsToUpdate[spl_object_hash($node)]);
  400. break;
  401. case self::ACTION_REMOVE:
  402. unset($this->pendingObjectsToRemove[spl_object_hash($node)]);
  403. break;
  404. default:
  405. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  406. }
  407. if (empty($this->pendingObjectsToInsert) && empty($this->pendingObjectsToUpdate) &&
  408. empty($this->pendingObjectsToRemove)) {
  409. $this->releaseTreeLocks($om, $ea);
  410. }
  411. }
  412. }
  413. /**
  414. * Locks all needed trees
  415. *
  416. * @param ObjectManager $om
  417. * @param AdapterInterface $ea
  418. *
  419. * @return void
  420. */
  421. protected function lockTrees(ObjectManager $om, AdapterInterface $ea)
  422. {
  423. // Do nothing by default
  424. }
  425. /**
  426. * Releases all trees which are locked
  427. *
  428. * @param ObjectManager $om
  429. * @param AdapterInterface $ea
  430. *
  431. * @return void
  432. */
  433. protected function releaseTreeLocks(ObjectManager $om, AdapterInterface $ea)
  434. {
  435. // Do nothing by default
  436. }
  437. /**
  438. * Remove node and its children
  439. *
  440. * @param ObjectManager $om
  441. * @param object $meta - Metadata
  442. * @param object $config - config
  443. * @param object $node - node to remove
  444. *
  445. * @return void
  446. */
  447. abstract public function removeNode($om, $meta, $config, $node);
  448. /**
  449. * Returns children of the node with its original path
  450. *
  451. * @param ObjectManager $om
  452. * @param object $meta - Metadata
  453. * @param object $config - config
  454. * @param string $originalPath - original path of object
  455. *
  456. * @return array|\Traversable
  457. */
  458. abstract public function getChildren($om, $meta, $config, $originalPath);
  459. }