AbstractMaterializedPath.php 15KB

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