ormlinkset.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once('dbobjectiterator.php');
  19. /**
  20. * The value for an attribute representing a set of links between the host object and "remote" objects
  21. *
  22. * @package iTopORM
  23. * @copyright Copyright (C) 2010-2017 Combodo SARL
  24. * @license http://opensource.org/licenses/AGPL-3.0
  25. */
  26. class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
  27. {
  28. protected $sHostClass; // subclass of DBObject
  29. protected $sAttCode; // xxxxxx_list
  30. protected $sClass; // class of the links
  31. /**
  32. * @var DBObjectSet
  33. */
  34. protected $oOriginalSet;
  35. /**
  36. * @var DBObject[] array of iObjectId => DBObject
  37. */
  38. protected $aOriginalObjects = null;
  39. /**
  40. * @var bool
  41. */
  42. protected $bHasDelta = false;
  43. /**
  44. * Object from the original set, minus the removed objects
  45. * @var DBObject[] array of iObjectId => DBObject
  46. */
  47. protected $aPreserved;
  48. /**
  49. * @var DBObject[] New items
  50. */
  51. protected $aAdded = array();
  52. /**
  53. * @var DBObject[] Modified items (could also be found in aPreserved)
  54. */
  55. protected $aModified = array();
  56. /**
  57. * @var int[] Removed items
  58. */
  59. protected $aRemoved = array();
  60. /**
  61. * @var int Position in the collection
  62. */
  63. protected $iCursor = 0;
  64. /**
  65. * ormLinkSet constructor.
  66. * @param $sHostClass
  67. * @param $sAttCode
  68. * @param DBObjectSet|null $oOriginalSet
  69. * @throws Exception
  70. */
  71. public function __construct($sHostClass, $sAttCode, DBObjectSet $oOriginalSet = null)
  72. {
  73. $this->sHostClass = $sHostClass;
  74. $this->sAttCode = $sAttCode;
  75. $this->oOriginalSet = $oOriginalSet ? clone $oOriginalSet : null;
  76. $oAttDef = MetaModel::GetAttributeDef($sHostClass, $sAttCode);
  77. if (!$oAttDef instanceof AttributeLinkedSet)
  78. {
  79. throw new Exception("ormLinkSet: $sAttCode is not a link set");
  80. }
  81. $this->sClass = $oAttDef->GetLinkedClass();
  82. if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass))
  83. {
  84. throw new Exception("ormLinkSet: wrong class for the original set, found {$oOriginalSet->GetClass()} while expecting {$oAttDef->GetLinkedClass()}");
  85. }
  86. }
  87. public function GetFilter()
  88. {
  89. return clone $this->oOriginalSet->GetFilter();
  90. }
  91. /**
  92. * Specify the subset of attributes to load (for each class of objects) before performing the SQL query for retrieving the rows from the DB
  93. *
  94. * @param hash $aAttToLoad Format: alias => array of attribute_codes
  95. *
  96. * @return void
  97. */
  98. public function OptimizeColumnLoad($aAttToLoad)
  99. {
  100. $this->oOriginalSet->OptimizeColumnLoad($aAttToLoad);
  101. }
  102. /**
  103. * @param DBObject $oLink
  104. */
  105. public function AddItem(DBObject $oLink)
  106. {
  107. assert($oLink instanceof $this->sClass);
  108. // No impact on the iteration algorithm
  109. $this->aAdded[] = $oLink;
  110. $this->bHasDelta = true;
  111. }
  112. /**
  113. * @param DBObject $oObject
  114. * @param string $sClassAlias
  115. * @deprecated
  116. */
  117. public function AddObject(DBObject $oObject, $sClassAlias = '')
  118. {
  119. trigger_error('iTop: ormLinkSet::AddObject() is deprecated use ormLinkSet::AddItem() instead.', E_USER_DEPRECATED);
  120. $this->AddItem($oObject);
  121. }
  122. /**
  123. * @param $iObjectId
  124. */
  125. public function RemoveItem($iObjectId)
  126. {
  127. if (array_key_exists($iObjectId, $this->aPreserved))
  128. {
  129. unset($this->aPreserved[$iObjectId]);
  130. $this->aRemoved[$iObjectId] = $iObjectId;
  131. $this->bHasDelta = true;
  132. }
  133. }
  134. /**
  135. * @param DBObject $oLink
  136. */
  137. public function ModifyItem(DBObject $oLink)
  138. {
  139. assert($oLink instanceof $this->sClass);
  140. $iObjectId = $oLink->GetKey();
  141. $this->aModified[$iObjectId] = $oLink;
  142. $this->bHasDelta = true;
  143. }
  144. protected function LoadOriginalIds()
  145. {
  146. if ($this->aOriginalObjects === null)
  147. {
  148. if ($this->oOriginalSet)
  149. {
  150. $this->aOriginalObjects = $this->oOriginalSet->ToArray();
  151. $this->aPreserved = $this->aOriginalObjects; // Copy (not effective until aPreserved gets modified)
  152. foreach ($this->aRemoved as $iObjectId)
  153. {
  154. if (array_key_exists($iObjectId, $this->aPreserved))
  155. {
  156. unset($this->aPreserved[$iObjectId]);
  157. }
  158. }
  159. }
  160. else
  161. {
  162. // Nothing to load
  163. $this->aOriginalObjects = array();
  164. $this->aPreserved = array();
  165. }
  166. }
  167. }
  168. /**
  169. * Note: After calling this method, the set cursor will be at the end of the set. You might to rewind it.
  170. *
  171. * @param bool $bWithId
  172. * @return array
  173. * @deprecated
  174. */
  175. public function ToArray($bWithId = true)
  176. {
  177. trigger_error('iTop: ormLinkSet::ToArray() is deprecated use foreach instead.', E_USER_DEPRECATED);
  178. $aRet = array();
  179. foreach($this as $oItem)
  180. {
  181. if ($bWithId)
  182. {
  183. $aRet[$oItem->GetKey()] = $oItem;
  184. }
  185. else
  186. {
  187. $aRet[] = $oItem;
  188. }
  189. }
  190. return $aRet;
  191. }
  192. /**
  193. * The class of the objects of the collection (at least a common ancestor)
  194. *
  195. * @return string
  196. */
  197. public function GetClass()
  198. {
  199. return $this->sClass;
  200. }
  201. /**
  202. * The total number of objects in the collection
  203. *
  204. * @return int
  205. */
  206. public function Count()
  207. {
  208. $this->LoadOriginalIds();
  209. $iRet = count($this->aPreserved) + count($this->aAdded);
  210. return $iRet;
  211. }
  212. /**
  213. * Position the cursor to the given 0-based position
  214. *
  215. * @param $iPosition
  216. * @throws Exception
  217. * @internal param int $iRow
  218. */
  219. public function Seek($iPosition)
  220. {
  221. $this->LoadOriginalIds();
  222. $iCount = $this->Count();
  223. if ($iPosition >= $iCount)
  224. {
  225. throw new Exception("Invalid position $iPosition: the link set is made of $iCount items.");
  226. }
  227. $this->rewind();
  228. for($iPos = 0 ; $iPos < $iPosition ; $iPos++)
  229. {
  230. $this->next();
  231. }
  232. }
  233. /**
  234. * Fetch the object at the current position in the collection and move the cursor to the next position.
  235. *
  236. * @return DBObject|null The fetched object or null when at the end
  237. */
  238. public function Fetch()
  239. {
  240. $this->LoadOriginalIds();
  241. $ret = $this->current();
  242. if ($ret === false)
  243. {
  244. $ret = null;
  245. }
  246. $this->next();
  247. return $ret;
  248. }
  249. /**
  250. * Return the current element
  251. * @link http://php.net/manual/en/iterator.current.php
  252. * @return mixed Can return any type.
  253. */
  254. public function current()
  255. {
  256. $this->LoadOriginalIds();
  257. $iPreservedCount = count($this->aPreserved);
  258. if ($this->iCursor < $iPreservedCount)
  259. {
  260. $oRet = current($this->aPreserved);
  261. }
  262. else
  263. {
  264. $oRet = current($this->aAdded);
  265. }
  266. return $oRet;
  267. }
  268. /**
  269. * Move forward to next element
  270. * @link http://php.net/manual/en/iterator.next.php
  271. * @return void Any returned value is ignored.
  272. */
  273. public function next()
  274. {
  275. $this->LoadOriginalIds();
  276. $iPreservedCount = count($this->aPreserved);
  277. if ($this->iCursor < $iPreservedCount)
  278. {
  279. next($this->aPreserved);
  280. }
  281. else
  282. {
  283. next($this->aAdded);
  284. }
  285. // Increment AFTER moving the internal cursors because when starting aAdded, we must leave it intact
  286. $this->iCursor++;
  287. }
  288. /**
  289. * Return the key of the current element
  290. * @link http://php.net/manual/en/iterator.key.php
  291. * @return mixed scalar on success, or null on failure.
  292. */
  293. public function key()
  294. {
  295. return $this->iCursor;
  296. }
  297. /**
  298. * Checks if current position is valid
  299. * @link http://php.net/manual/en/iterator.valid.php
  300. * @return boolean The return value will be casted to boolean and then evaluated.
  301. * Returns true on success or false on failure.
  302. */
  303. public function valid()
  304. {
  305. $this->LoadOriginalIds();
  306. $iCount = $this->Count();
  307. $bRet = ($this->iCursor < $iCount);
  308. return $bRet;
  309. }
  310. /**
  311. * Rewind the Iterator to the first element
  312. * @link http://php.net/manual/en/iterator.rewind.php
  313. * @return void Any returned value is ignored.
  314. */
  315. public function rewind()
  316. {
  317. $this->LoadOriginalIds();
  318. $this->iCursor = 0;
  319. reset($this->aPreserved);
  320. reset($this->aAdded);
  321. }
  322. public function HasDelta()
  323. {
  324. return $this->bHasDelta;
  325. }
  326. /**
  327. * This method has been designed specifically for AttributeLinkedSet:Equals and as such it assumes that the passed argument is a clone of this.
  328. * @param ormLinkSet $oFellow
  329. * @return bool|null
  330. * @throws Exception
  331. */
  332. public function Equals(ormLinkSet $oFellow)
  333. {
  334. $bRet = null;
  335. if ($this === $oFellow)
  336. {
  337. $bRet = true;
  338. }
  339. else
  340. {
  341. if ( ($this->oOriginalSet !== $oFellow->oOriginalSet)
  342. && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
  343. {
  344. throw new Exception('ormLinkSet::Equals assumes that compared link sets have the same original scope');
  345. }
  346. if ($this->HasDelta())
  347. {
  348. throw new Exception('ormLinkSet::Equals assumes that left link set had no delta');
  349. }
  350. $bRet = !$oFellow->HasDelta();
  351. }
  352. return $bRet;
  353. }
  354. public function UpdateFromCompleteList(iDBObjectSetIterator $oFellow)
  355. {
  356. if ($oFellow === $this)
  357. {
  358. throw new Exception('ormLinkSet::UpdateFromCompleteList assumes that the passed link set is at least a clone of the current one');
  359. }
  360. $bUpdateFromDelta = false;
  361. if ($oFellow instanceof ormLinkSet)
  362. {
  363. if ( ($this->oOriginalSet === $oFellow->oOriginalSet)
  364. || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
  365. {
  366. $bUpdateFromDelta = true;
  367. }
  368. }
  369. if ($bUpdateFromDelta)
  370. {
  371. // Same original set -> simply update the delta
  372. $this->iCursor = 0;
  373. $this->aAdded = $oFellow->aAdded;
  374. $this->aRemoved = $oFellow->aRemoved;
  375. $this->aModified = $oFellow->aModified;
  376. $this->aPreserved = $oFellow->aPreserved;
  377. $this->bHasDelta = $oFellow->bHasDelta;
  378. }
  379. else
  380. {
  381. // For backward compatibility reasons, let's rebuild a delta...
  382. // Reset the delta
  383. $this->iCursor = 0;
  384. $this->aAdded = array();
  385. $this->aRemoved = array();
  386. $this->aModified = array();
  387. $this->aPreserved = $this->aOriginalObjects;
  388. $this->bHasDelta = false;
  389. /** @var AttributeLinkedSet $oAttDef */
  390. $oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode);
  391. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  392. $sAdditionalKey = null;
  393. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  394. {
  395. $sAdditionalKey = $oAttDef->GetExtKeyToRemote();
  396. }
  397. // Compare both collections by iterating the whole sets, order them, a build a fingerprint based on meaningful data (what make the difference)
  398. $oComparator = new DBObjectSetComparator($this, $oFellow, array($sExtKeyToMe), $sAdditionalKey);
  399. $aChanges = $oComparator->GetDifferences();
  400. foreach ($aChanges['added'] as $oLink)
  401. {
  402. $this->AddItem($oLink);
  403. }
  404. foreach ($aChanges['modified'] as $oLink)
  405. {
  406. $this->ModifyItem($oLink);
  407. }
  408. foreach ($aChanges['removed'] as $oLink)
  409. {
  410. $this->RemoveItem($oLink->GetKey());
  411. }
  412. }
  413. }
  414. /**
  415. * @param DBObject $oHostObject
  416. */
  417. public function DBWrite(DBObject $oHostObject)
  418. {
  419. /** @var AttributeLinkedSet $oAttDef */
  420. $oAttDef = MetaModel::GetAttributeDef(get_class($oHostObject), $this->sAttCode);
  421. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  422. $sExtKeyToRemote = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote() : 'n/a';
  423. $aCheckLinks = array();
  424. $aCheckRemote = array();
  425. foreach ($this->aAdded as $oLink)
  426. {
  427. if ($oLink->IsNew())
  428. {
  429. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  430. {
  431. //todo: faire un test qui passe dans cette branche !
  432. $aCheckRemote[] = $oLink->Get($sExtKeyToRemote);
  433. }
  434. }
  435. else
  436. {
  437. //todo: faire un test qui passe dans cette branche !
  438. $aCheckLinks[] = $oLink->GetKey();
  439. }
  440. }
  441. foreach ($this->aRemoved as $iLinkId)
  442. {
  443. $aCheckLinks[] = $iLinkId;
  444. }
  445. foreach ($this->aModified as $iLinkId => $oLink)
  446. {
  447. $aCheckLinks[] = $oLink->GetKey();
  448. }
  449. // Critical section : serialize any write access to these links
  450. //
  451. $oMtx = new iTopMutex('Write-'.$this->sClass);
  452. $oMtx->Lock();
  453. // Check for the existing links
  454. //
  455. if (count($aCheckLinks) > 0)
  456. {
  457. $oSearch = new DBObjectSearch($this->sClass);
  458. $oSearch->AddCondition('id', $aCheckLinks, 'IN');
  459. $oSet = new DBObjectSet($oSearch);
  460. /** @var DBObject[] $aExistingLinks */
  461. $aExistingLinks = $oSet->ToArray();
  462. }
  463. // Check for the existing remote objects
  464. //
  465. if (count($aCheckRemote) > 0)
  466. {
  467. $oSearch = new DBObjectSearch($this->sClass);
  468. $oSearch->AddCondition($sExtKeyToMe, $oHostObject->GetKey(), '=');
  469. $oSearch->AddCondition($sExtKeyToRemote, $aCheckRemote, 'IN');
  470. $oSet = new DBObjectSet($oSearch);
  471. /** @var Int[] $aExistingRemote */
  472. $aExistingRemote = $oSet->GetColumnAsArray($sExtKeyToRemote);
  473. }
  474. // Write the links according to the existing links
  475. //
  476. foreach ($this->aAdded as $oLink)
  477. {
  478. // Make sure that the objects in the set point to "this"
  479. $oLink->Set($sExtKeyToMe, $oHostObject->GetKey());
  480. if ($oLink->IsNew())
  481. {
  482. if (count($aCheckRemote) > 0)
  483. {
  484. if (in_array($oLink->Get($sExtKeyToRemote), $aExistingRemote))
  485. {
  486. // Do not create a duplicate
  487. continue;
  488. }
  489. }
  490. }
  491. else
  492. {
  493. if (!array_key_exists($oLink->GetKey(), $aExistingLinks))
  494. {
  495. $oLink->DBClone();
  496. }
  497. }
  498. $oLink->DBWrite();
  499. }
  500. foreach ($this->aRemoved as $iLinkId)
  501. {
  502. if (array_key_exists($iLinkId, $aExistingLinks))
  503. {
  504. $oLink = $aExistingLinks[$iLinkId];
  505. if ($oAttDef->IsIndirect())
  506. {
  507. $oLink->DBDelete();
  508. }
  509. else
  510. {
  511. $oExtKeyToRemote = MetaModel::GetAttributeDef($this->sClass, $sExtKeyToMe);
  512. if ($oExtKeyToRemote->IsNullAllowed())
  513. {
  514. if ($oLink->Get($sExtKeyToMe) == $oHostObject->GetKey())
  515. {
  516. // Detach the link object from this
  517. $oLink->Set($sExtKeyToMe, 0);
  518. $oLink->DBUpdate();
  519. }
  520. }
  521. else
  522. {
  523. $oLink->DBDelete();
  524. }
  525. }
  526. }
  527. }
  528. // Note: process modifications at the end: if a link to remove has also been listed as modified, then it will be gracefully ignored
  529. foreach ($this->aModified as $iLinkId => $oLink)
  530. {
  531. if (array_key_exists($oLink->GetKey(), $aExistingLinks))
  532. {
  533. $oLink->DBUpdate();
  534. }
  535. else
  536. {
  537. $oLink->DBClone();
  538. }
  539. }
  540. // End of the critical section
  541. //
  542. $oMtx->Unlock();
  543. }
  544. }