AbstractMaterializedPath.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. $changeSet = $uow->isScheduledForUpdate($parent) ? $ea->getObjectChangeSet($uow, $parent) : false;
  236. $pathOrPathSourceHasChanged = $changeSet && (isset($changeSet[$config['path_source']]) || isset($changeSet[$config['path']]));
  237. if ($pathOrPathSourceHasChanged || !$pathProp->getValue($parent)) {
  238. $this->updateNode($om, $parent, $ea);
  239. }
  240. $path = $pathProp->getValue($parent).$path;
  241. }
  242. $pathProp->setValue($node, $path);
  243. $changes = array(
  244. $config['path'] => array(null, $path)
  245. );
  246. if (isset($config['level'])) {
  247. $level = substr_count($path, $config['path_separator']);
  248. $levelProp = $meta->getReflectionProperty($config['level']);
  249. $levelProp->setAccessible(true);
  250. $levelProp->setValue($node, $level);
  251. $changes[$config['level']] = array(null, $level);
  252. }
  253. $uow->scheduleExtraUpdate($node, $changes);
  254. $ea->setOriginalObjectProperty($uow, $oid, $config['path'], $path);
  255. }
  256. /**
  257. * Update node's children
  258. *
  259. * @param ObjectManager $om
  260. * @param object $node
  261. * @param AdapterInterface $ea
  262. * @param string $originalPath
  263. * @return void
  264. */
  265. public function updateChildren(ObjectManager $om, $node, AdapterInterface $ea, $originalPath)
  266. {
  267. $meta = $om->getClassMetadata(get_class($node));
  268. $config = $this->listener->getConfiguration($om, $meta->name);
  269. $children = $this->getChildren($om, $meta, $config, $originalPath);
  270. foreach ($children as $child) {
  271. $this->updateNode($om, $child, $ea);
  272. }
  273. }
  274. /**
  275. * Process pre-locking actions
  276. *
  277. * @param ObjectManager $om
  278. * @param object $node
  279. * @param string $action
  280. * @return void
  281. */
  282. public function processPreLockingActions($om, $node, $action)
  283. {
  284. $meta = $om->getClassMetadata(get_class($node));
  285. $config = $this->listener->getConfiguration($om, $meta->name);
  286. if ($config['activate_locking']) {;
  287. $parentProp = $meta->getReflectionProperty($config['parent']);
  288. $parentProp->setAccessible(true);
  289. $parentNode = $node;
  290. while (!is_null($parent = $parentProp->getValue($parentNode))) {
  291. $parentNode = $parent;
  292. }
  293. // In some cases, the parent could be a not initialized proxy. In this case, the
  294. // "lockTime" field may NOT be loaded yet and have null instead of the date.
  295. // We need to be sure that this field has its real value
  296. if ($parentNode !== $node && $parentNode instanceof \Doctrine\ODM\MongoDB\Proxy\Proxy) {
  297. $reflMethod = new \ReflectionMethod(get_class($parentNode), '__load');
  298. $reflMethod->setAccessible(true);
  299. $reflMethod->invoke($parentNode);
  300. }
  301. // If tree is already locked, we throw an exception
  302. $lockTimeProp = $meta->getReflectionProperty($config['lock_time']);
  303. $lockTimeProp->setAccessible(true);
  304. $lockTime = $lockTimeProp->getValue($parentNode);
  305. if (!is_null($lockTime)) {
  306. $lockTime = $lockTime instanceof \MongoDate ? $lockTime->sec : $lockTime->getTimestamp();
  307. }
  308. if (!is_null($lockTime) && ($lockTime >= (time() - $config['locking_timeout']))) {
  309. $msg = 'Tree with root id "%s" is locked.';
  310. $id = $meta->getIdentifierValue($parentNode);
  311. throw new TreeLockingException(sprintf($msg, $id));
  312. }
  313. $this->rootsOfTreesWhichNeedsLocking[spl_object_hash($parentNode)] = $parentNode;
  314. $oid = spl_object_hash($node);
  315. switch ($action) {
  316. case self::ACTION_INSERT:
  317. $this->pendingObjectsToInsert[$oid] = $node;
  318. break;
  319. case self::ACTION_UPDATE:
  320. $this->pendingObjectsToUpdate[$oid] = $node;
  321. break;
  322. case self::ACTION_REMOVE:
  323. $this->pendingObjectsToRemove[$oid] = $node;
  324. break;
  325. default:
  326. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  327. }
  328. }
  329. }
  330. /**
  331. * Process pre-locking actions
  332. *
  333. * @param ObjectManager $om
  334. * @param AdapterInterface $ea
  335. * @param object $node
  336. * @param string $action
  337. * @return void
  338. */
  339. public function processPostEventsActions(ObjectManager $om, AdapterInterface $ea, $node, $action)
  340. {
  341. $meta = $om->getClassMetadata(get_class($node));
  342. $config = $this->listener->getConfiguration($om, $meta->name);
  343. if ($config['activate_locking']) {
  344. switch ($action) {
  345. case self::ACTION_INSERT:
  346. unset($this->pendingObjectsToInsert[spl_object_hash($node)]);
  347. break;
  348. case self::ACTION_UPDATE:
  349. unset($this->pendingObjectsToUpdate[spl_object_hash($node)]);
  350. break;
  351. case self::ACTION_REMOVE:
  352. unset($this->pendingObjectsToRemove[spl_object_hash($node)]);
  353. break;
  354. default:
  355. throw new \InvalidArgumentException(sprintf('"%s" is not a valid action.', $action));
  356. }
  357. if (empty($this->pendingObjectsToInsert) && empty($this->pendingObjectsToUpdate) &&
  358. empty($this->pendingObjectsToRemove)) {
  359. $this->releaseTreeLocks($om, $ea);
  360. }
  361. }
  362. }
  363. /**
  364. * Locks all needed trees
  365. *
  366. * @param ObjectManager $om
  367. * @param AdapterInterface $ea
  368. * @return void
  369. */
  370. protected function lockTrees(ObjectManager $om, AdapterInterface $ea)
  371. {
  372. // Do nothing by default
  373. }
  374. /**
  375. * Releases all trees which are locked
  376. *
  377. * @param ObjectManager $om
  378. * @param AdapterInterface $ea
  379. * @return void
  380. */
  381. protected function releaseTreeLocks(ObjectManager $om, AdapterInterface $ea)
  382. {
  383. // Do nothing by default
  384. }
  385. /**
  386. * Remove node and its children
  387. *
  388. * @param ObjectManager $om
  389. * @param object $meta - Metadata
  390. * @param object $config - config
  391. * @param object $node - node to remove
  392. * @return void
  393. */
  394. abstract public function removeNode($om, $meta, $config, $node);
  395. /**
  396. * Returns children of the node with its original path
  397. *
  398. * @param ObjectManager $om
  399. * @param object $meta - Metadata
  400. * @param object $config - config
  401. * @param string $originalPath - original path of object
  402. * @return Doctrine\ODM\MongoDB\Cursor
  403. */
  404. abstract public function getChildren($om, $meta, $config, $originalPath);
  405. }