simplegraph.class.inc.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. <?php
  2. // Copyright (C) 2015 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. /**
  19. * Data structures (i.e. PHP classes) to manage "graphs"
  20. *
  21. * @copyright Copyright (C) 2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. *
  24. * Example:
  25. * require_once('../approot.inc.php');
  26. * require_once(APPROOT.'application/startup.inc.php');
  27. * require_once(APPROOT.'core/simplegraph.class.inc.php');
  28. *
  29. * $oGraph = new SimpleGraph();
  30. *
  31. * $oNode1 = new GraphNode($oGraph, 'Source1');
  32. * $oNode2 = new GraphNode($oGraph, 'Sink');
  33. * $oEdge1 = new GraphEdge($oGraph, 'flow1', $oNode1, $oNode2);
  34. * $oNode3 = new GraphNode($oGraph, 'Source2');
  35. * $oEdge2 = new GraphEdge($oGraph, 'flow2', $oNode3, $oNode2);
  36. * $oEdge2 = new GraphEdge($oGraph, 'flow3', $oNode2, $oNode3);
  37. * $oEdge2 = new GraphEdge($oGraph, 'flow4', $oNode1, $oNode3);
  38. *
  39. * echo $oGraph->DumpAsHtmlImage(); // requires graphviz
  40. * echo $oGraph->DumpAsHtmlText();
  41. */
  42. /**
  43. * Exceptions generated by the SimpleGraph class
  44. */
  45. class SimpleGraphException extends Exception
  46. {
  47. }
  48. /**
  49. * The parent class of all elements which can be part of a SimpleGraph
  50. */
  51. class GraphElement
  52. {
  53. protected $sId;
  54. protected $aProperties;
  55. /**
  56. * Constructor
  57. * @param string $sId The identifier of the object in the graph
  58. */
  59. public function __construct($sId)
  60. {
  61. $this->sId = $sId;
  62. $this->aProperties = array();
  63. }
  64. /**
  65. * Get the identifier of the object in the graph
  66. * @return string
  67. */
  68. public function GetId()
  69. {
  70. return $this->sId;
  71. }
  72. /**
  73. * Get the value of the given named property for the object
  74. * @param string $sPropName The name of the property to get
  75. * @param mixed $defaultValue The default value to return if the property does not exist
  76. * @return mixed
  77. */
  78. public function GetProperty($sPropName, $defaultValue = null)
  79. {
  80. return array_key_exists($sPropName, $this->aProperties) ? $this->aProperties[$sPropName] : $defaultValue;
  81. }
  82. /**
  83. * Set the value of a named property for the object
  84. * @param string $sPropName The name of the property to set
  85. * @param mixed $value
  86. * @return void
  87. */
  88. public function SetProperty($sPropName, $value)
  89. {
  90. $this->aProperties[$sPropName] = $value;
  91. }
  92. /**
  93. * Get all the known properties of the object
  94. * @return Ambigous <multitype:, mixed>
  95. */
  96. public function GetProperties()
  97. {
  98. return $this->aProperties;
  99. }
  100. }
  101. /**
  102. * A Node inside a SimpleGraph
  103. */
  104. class GraphNode extends GraphElement
  105. {
  106. protected $aIncomingEdges;
  107. protected $aOutgoingEdges;
  108. /**
  109. * Create a new node inside a graph
  110. * @param SimpleGraph $oGraph
  111. * @param string $sId The unique identifier of this node inside the graph
  112. */
  113. public function __construct(SimpleGraph $oGraph, $sId)
  114. {
  115. parent::__construct($sId);
  116. $this->aIncomingEdges = array();
  117. $this->aOutgoingEdges = array();
  118. $oGraph->_AddNode($this);
  119. }
  120. public function GetDotAttributes()
  121. {
  122. $sLabel = addslashes($this->GetProperty('label', $this->GetId()));
  123. $sDot = 'label="'.$sLabel.'"';
  124. return $sDot;
  125. }
  126. /**
  127. * INTERNAL USE ONLY
  128. * @param GraphEdge $oEdge
  129. */
  130. public function _AddIncomingEdge(GraphEdge $oEdge)
  131. {
  132. $this->aIncomingEdges[$oEdge->GetId()] = $oEdge;
  133. }
  134. /**
  135. * INTERNAL USE ONLY
  136. * @param GraphEdge $oEdge
  137. */
  138. public function _AddOutgoingEdge(GraphEdge $oEdge)
  139. {
  140. $this->aOutgoingEdges[$oEdge->GetId()] = $oEdge;
  141. }
  142. /**
  143. * INTERNAL USE ONLY
  144. * @param GraphEdge $oEdge
  145. */
  146. public function _RemoveIncomingEdge(GraphEdge $oEdge)
  147. {
  148. unset($this->aIncomingEdges[$oEdge->GetId()]);
  149. }
  150. /**
  151. * INTERNAL USE ONLY
  152. * @param GraphEdge $oEdge
  153. */
  154. public function _RemoveOutgoingEdge(GraphEdge $oEdge)
  155. {
  156. unset($this->aOutgoingEdges[$oEdge->GetId()]);
  157. }
  158. /**
  159. * Get the list of all incoming edges on the current node
  160. * @return Ambigous <multitype:, GraphEdge>
  161. */
  162. public function GetIncomingEdges()
  163. {
  164. return $this->aIncomingEdges;
  165. }
  166. /**
  167. * Get the list of all outgoing edges from the current node
  168. * @return Ambigous <multitype:, GraphEdge>
  169. */
  170. public function GetOutgoingEdges()
  171. {
  172. return $this->aOutgoingEdges;
  173. }
  174. /**
  175. * Flood fill the chart with the given value for the specified property
  176. * @param string $sPropName The name of the property to set
  177. * @param mixed $value Teh value to set in the property
  178. * @param bool $bFloodDown Whether or not to fill in the downstream direction
  179. * @param bool $bFloodUp Whether or not to fill in the upstream direction
  180. */
  181. public function FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp)
  182. {
  183. if ($this->GetProperty($sPropName, null) == null)
  184. {
  185. // Property not already set, let's do it
  186. $this->SetProperty($sPropName, $value);
  187. if ($bFloodDown)
  188. {
  189. foreach($this->GetOutgoingEdges() as $oEdge)
  190. {
  191. $oEdge->SetProperty($sPropName, $value);
  192. $oEdge->GetSinkNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
  193. }
  194. }
  195. if ($bFloodUp)
  196. {
  197. foreach($this->GetIncomingEdges() as $oEdge)
  198. {
  199. $oEdge->SetProperty($sPropName, $value);
  200. $oEdge->GetSourceNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
  201. }
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * A directed Edge inside a SimpleGraph
  208. */
  209. class GraphEdge extends GraphElement
  210. {
  211. protected $oSourceNode;
  212. protected $oSinkNode;
  213. /**
  214. * Create a new directed edge inside the given graph
  215. * @param SimpleGraph $oGraph
  216. * @param string $sId The unique identifier of this edge in the graph
  217. * @param GraphNode $oSourceNode
  218. * @param GraphNode $oSinkNode
  219. */
  220. public function __construct(SimpleGraph $oGraph, $sId, GraphNode $oSourceNode, GraphNode $oSinkNode)
  221. {
  222. parent::__construct($sId);
  223. $this->oSourceNode = $oSourceNode;
  224. $this->oSinkNode = $oSinkNode;
  225. $oGraph->_AddEdge($this);
  226. }
  227. /**
  228. * Get the "source" node for this edge
  229. * @return GraphNode
  230. */
  231. public function GetSourceNode()
  232. {
  233. return $this->oSourceNode;
  234. }
  235. /**
  236. * Get the "sink" node for this edge
  237. * @return GraphNode
  238. */
  239. public function GetSinkNode()
  240. {
  241. return $this->oSinkNode;
  242. }
  243. public function GetDotAttributes()
  244. {
  245. $sLabel = addslashes($this->GetProperty('label', ''));
  246. $sDot = 'label="'.$sLabel.'"';
  247. return $sDot;
  248. }
  249. }
  250. /**
  251. * The main container for a graph: SimpleGraph
  252. */
  253. class SimpleGraph
  254. {
  255. protected $aNodes;
  256. protected $aEdges;
  257. /**
  258. * Creates a new empty graph
  259. */
  260. public function __construct()
  261. {
  262. $this->aNodes = array();
  263. $this->aEdges = array();
  264. }
  265. /**
  266. * INTERNAL USE ONLY
  267. * @return Ambigous <multitype:, GraphNode>
  268. */
  269. public function _GetNodes()
  270. {
  271. return $this->aNodes;
  272. }
  273. /**
  274. * INTERNAL USE ONLY
  275. * @return Ambigous <multitype:, GraphNode>
  276. */
  277. public function _GetEdges()
  278. {
  279. return $this->aEdges;
  280. }
  281. /**
  282. * INTERNAL USE ONLY
  283. * @return Ambigous <multitype:, GraphNode>
  284. */
  285. public function _AddNode(GraphNode $oNode)
  286. {
  287. if (array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists in the graph.');
  288. $this->aNodes[$oNode->GetId()] = $oNode;
  289. }
  290. /**
  291. * INTERNAL USE ONLY
  292. * @return Ambigous <multitype:, GraphNode>
  293. */
  294. public function _RemoveNode(GraphNode $oNode)
  295. {
  296. if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
  297. foreach($oNode->GetOutgoingEdges() as $oEdge)
  298. {
  299. $this->_RemoveEdge($oEdge);
  300. }
  301. foreach($oNode->GetIncomingEdges() as $oEdge)
  302. {
  303. $this->_RemoveEdge($oEdge);
  304. }
  305. unset($this->aNodes[$oNode->GetId()]);
  306. }
  307. /**
  308. * Removes the given node but preserves the connectivity of the graph
  309. * all "source" nodes are connected to all "sink" nodes
  310. * @param GraphNode $oNode
  311. * @throws SimpleGraphException
  312. */
  313. public function FilterNode(GraphNode $oNode)
  314. {
  315. if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
  316. $aSourceNodes = array();
  317. $aSinkNodes = array();
  318. foreach($oNode->GetOutgoingEdges() as $oEdge)
  319. {
  320. $sSinkId = $oEdge->GetSinkNode()->GetId();
  321. $aSinkNodes[$sSinkId] = $oEdge->GetSinkNode();
  322. $this->_RemoveEdge($oEdge);
  323. }
  324. foreach($oNode->GetIncomingEdges() as $oEdge)
  325. {
  326. $sSourceId = $oEdge->GetSourceNode()->GetId();
  327. $aSourceNodes[$sSourceId] = $oEdge->GetSourceNode();
  328. $this->_RemoveEdge($oEdge);
  329. }
  330. unset($this->aNodes[$oNode->GetId()]);
  331. foreach($aSourceNodes as $sSourceId => $oSourceNode)
  332. {
  333. foreach($aSinkNodes as $sSinkId => $oSinkNode)
  334. {
  335. $oEdge = new RelationEdge($this, $oSourceNode, $oSinkNode);
  336. }
  337. }
  338. }
  339. /**
  340. * Get the node identified by $sId or null if not found
  341. * @param string $sId
  342. * @return NULL | GraphNode
  343. */
  344. public function GetNode($sId)
  345. {
  346. return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
  347. }
  348. /**
  349. * Determine if the id already exists in amongst the existing nodes
  350. * @param string $sId
  351. * @return boolean
  352. */
  353. public function HasNode($sId)
  354. {
  355. return array_key_exists($sId, $this->aNodes);
  356. }
  357. /**
  358. * INTERNAL USE ONLY
  359. * @param GraphEdge $oEdge
  360. * @throws SimpleGraphException
  361. */
  362. public function _AddEdge(GraphEdge $oEdge)
  363. {
  364. if (array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot add edge (id='.$oEdge->GetId().') to the graph. An edge with the same id already exists in the graph.');
  365. $this->aEdges[$oEdge->GetId()] = $oEdge;
  366. $oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge);
  367. $oEdge->GetSinkNode()->_AddIncomingEdge($oEdge);
  368. }
  369. /**
  370. * INTERNAL USE ONLY
  371. * @param GraphEdge $oEdge
  372. * @throws SimpleGraphException
  373. */
  374. public function _RemoveEdge(GraphEdge $oEdge)
  375. {
  376. if (!array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.');
  377. $oEdge->GetSourceNode()->_RemoveOutgoingEdge($oEdge);
  378. $oEdge->GetSinkNode()->_RemoveIncomingEdge($oEdge);
  379. unset($this->aEdges[$oEdge->GetId()]);
  380. }
  381. /**
  382. * Get the edge indentified by $sId or null if not found
  383. * @param string $sId
  384. * @return NULL | GraphEdge
  385. */
  386. public function GetEdge($sId)
  387. {
  388. return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null;
  389. }
  390. /**
  391. * Determine if the id already exists in amongst the existing edges
  392. * @param string $sId
  393. * @return boolean
  394. */
  395. public function HasEdge($sId)
  396. {
  397. return array_key_exists($sId, $this->aEdges);
  398. }
  399. /**
  400. * Get the description of the graph as a text string in the graphviz 'dot' language
  401. * @return string
  402. */
  403. public function GetDotDescription()
  404. {
  405. $sDot =
  406. <<<EOF
  407. digraph finite_state_machine {
  408. graph [bgcolor = "transparent"];
  409. rankdir=LR;
  410. size="30,30";
  411. fontsize=8.0;
  412. node [ fontname=Verdana style=filled fillcolor="#ffffcc" fontsize=8.0 ];
  413. edge [ fontname=Verdana ];
  414. EOF
  415. ;
  416. $oIterator = new RelationTypeIterator($this, 'Node');
  417. foreach($oIterator as $key => $oNode)
  418. {
  419. $sDot .= "\t\"".$oNode->GetId()."\" [ ".$oNode->GetDotAttributes()." ];\n";
  420. if (count($oNode->GetOutgoingEdges()) > 0)
  421. {
  422. foreach($oNode->GetOutgoingEdges() as $oEdge)
  423. {
  424. $sDot .= "\t\"".$oNode->GetId()."\" -> \"".$oEdge->GetSinkNode()->GetId()."\" [ ".$oEdge->GetDotAttributes()." ];\n";
  425. }
  426. }
  427. }
  428. $sDot .= "}\n";
  429. return $sDot;
  430. }
  431. /**
  432. * Get the description of the graph as an embedded PNG image (using a data: url) as
  433. * generated by graphviz (requires graphviz to be installed on the machine and the path to
  434. * dot/dot.exe to be configured in the iTop configuration file)
  435. * Note: the function creates temporary files in APPROOT/data/tmp
  436. * @return string
  437. */
  438. public function DumpAsHtmlImage()
  439. {
  440. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  441. if (file_exists($sDotExecutable))
  442. {
  443. // create the file with Graphviz
  444. if (!is_dir(APPROOT."data"))
  445. {
  446. @mkdir(APPROOT."data");
  447. }
  448. if (!is_dir(APPROOT."data/tmp"))
  449. {
  450. @mkdir(APPROOT."data/tmp");
  451. }
  452. $sImageFilePath = tempnam(APPROOT."data/tmp", 'png-');
  453. $sDotDescription = $this->GetDotDescription();
  454. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  455. $rFile = @fopen($sDotFilePath, "w");
  456. @fwrite($rFile, $sDotDescription);
  457. @fclose($rFile);
  458. $aOutput = array();
  459. $CommandLine = "\"$sDotExecutable\" -v -Tpng < $sDotFilePath -o$sImageFilePath 2>&1";
  460. exec($CommandLine, $aOutput, $iRetCode);
  461. if ($iRetCode != 0)
  462. {
  463. $sHtml = '';
  464. $sHtml .= "<p><b>Error:</b></p>";
  465. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  466. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  467. $sHtml .= "<hr>";
  468. $sHtml .= "<p>Content of the '".basename($sDotFilePath)."' file:<pre>\n$sDotDescription</pre>";
  469. }
  470. else
  471. {
  472. $sHtml = '<img src="data:image/png;base64,'.base64_encode(file_get_contents($sImageFilePath)).'">';
  473. @unlink($sImageFilePath);
  474. }
  475. @unlink($sDotFilePath);
  476. }
  477. else
  478. {
  479. throw new Exception('graphviz not found (executable path: '.$sDotExecutable.')');
  480. }
  481. return $sHtml;
  482. }
  483. /**
  484. * Get the description of the graph as text string in the XDot format
  485. * including the positions of the nodes and egdes (requires graphviz
  486. * to be installed on the machine and the path to dot/dot.exe to be
  487. * configured in the iTop configuration file)
  488. * Note: the function creates temporary files in APPROOT/data/tmp
  489. * @return string
  490. */
  491. public function DumpAsXDot()
  492. {
  493. $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
  494. if (file_exists($sDotExecutable))
  495. {
  496. // create the file with Graphviz
  497. if (!is_dir(APPROOT."data"))
  498. {
  499. @mkdir(APPROOT."data");
  500. }
  501. if (!is_dir(APPROOT."data/tmp"))
  502. {
  503. @mkdir(APPROOT."data/tmp");
  504. }
  505. $sXdotFilePath = tempnam(APPROOT."data/tmp", 'xdot-');
  506. $sDotDescription = $this->GetDotDescription();
  507. $sDotFilePath = tempnam(APPROOT."data/tmp", 'dot-');
  508. $rFile = @fopen($sDotFilePath, "w");
  509. @fwrite($rFile, $sDotDescription);
  510. @fclose($rFile);
  511. $aOutput = array();
  512. $CommandLine = "\"$sDotExecutable\" -v -Tdot < $sDotFilePath -o$sXdotFilePath 2>&1";
  513. exec($CommandLine, $aOutput, $iRetCode);
  514. if ($iRetCode != 0)
  515. {
  516. $sHtml = '';
  517. $sHtml .= "<p><b>Error:</b></p>";
  518. $sHtml .= "<p>The command: <pre>$CommandLine</pre> returned $iRetCode</p>";
  519. $sHtml .= "<p>The output of the command is:<pre>\n".implode("\n", $aOutput)."</pre></p>";
  520. }
  521. else
  522. {
  523. $sHtml = '<pre>'.file_get_contents($sXdotFilePath).'</pre>';
  524. @unlink($sImageFilePath);
  525. }
  526. @unlink($sXdotFilePath);
  527. }
  528. else
  529. {
  530. throw new Exception('graphviz not found (executable path: '.$sDotExecutable.')');
  531. }
  532. return $sHtml;
  533. }
  534. /**
  535. * Get the description of the graph as some HTML text
  536. * @return string
  537. */
  538. public function DumpAsHTMLText()
  539. {
  540. $sHtml = '';
  541. $oIterator = new RelationTypeIterator($this);
  542. foreach($oIterator as $key => $oElement)
  543. {
  544. $sHtml .= "<p>$key: ".get_class($oElement)."::".$oElement->GetId()."</p>";
  545. switch(get_class($oElement))
  546. {
  547. case 'GraphNode':
  548. if (count($oElement->GetIncomingEdges()) > 0)
  549. {
  550. $sHtml .= "<ul>Incoming edges:\n";
  551. foreach($oElement->GetIncomingEdges() as $oEdge)
  552. {
  553. $sHtml .= "<li>From: ".$oEdge->GetSourceNode()->GetId()."</li>\n";
  554. }
  555. $sHtml .= "</ul>\n";
  556. }
  557. if (count($oElement->GetOutgoingEdges()) > 0)
  558. {
  559. $sHtml .= "<ul>Outgoing edges:\n";
  560. foreach($oElement->GetOutgoingEdges() as $oEdge)
  561. {
  562. $sHtml .= "<li>To: ".$oEdge->GetSinkNode()->GetId()."</li>\n";
  563. }
  564. $sHtml .= "</ul>\n";
  565. }
  566. break;
  567. case 'GraphEdge':
  568. $sHtml .= "<p>From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."</p>\n";
  569. break;
  570. }
  571. }
  572. return $sHtml;
  573. }
  574. /**
  575. * Split the graph in a array of non connected subgraphs
  576. * @return multitype:SimpleGraph unknown
  577. */
  578. public function GetSubgraphs()
  579. {
  580. $iNbColors = 0;
  581. $aResult = array();
  582. $oIterator = new RelationTypeIterator($this, 'Node');
  583. foreach($oIterator as $oNode)
  584. {
  585. $iPrevColor = $oNode->GetProperty('color', null);
  586. if ($iPrevColor == null)
  587. {
  588. $iNbColors++; // Start a new color
  589. $oNode->FloodProperty('color', $iNbColors, true, true);
  590. }
  591. }
  592. if ($iNbColors == 1)
  593. {
  594. // Everything is connected together, only one subgraph
  595. $aResult[] = $this;
  596. }
  597. else
  598. {
  599. // Let's reconstruct each separate graph
  600. $sClass = get_class($this);
  601. for($i = 1; $i <= $iNbColors; $i++)
  602. {
  603. $aResult[$i] = new $sClass();
  604. }
  605. foreach($oIterator as $oNode)
  606. {
  607. $iNodeColor = $oNode->GetProperty('color');
  608. $aResult[$iNodeColor]->_AddNode($oNode);
  609. }
  610. $oIter2 = new RelationTypeIterator($this, 'Edge');
  611. foreach($oIter2 as $oEdge)
  612. {
  613. $iEdgeColor = $oEdge->GetProperty('color');
  614. $aResult[$iEdgeColor]->_AddEdge($oEdge);
  615. }
  616. }
  617. return $aResult;
  618. }
  619. /**
  620. * Merge back to subgraphs into one
  621. * @param SimpleGraph $oGraph
  622. */
  623. public function Merge(SimpleGraph $oGraph)
  624. {
  625. $oIter1 = new RelationTypeIterator($oGraph, 'Node');
  626. foreach($oIter1 as $oNode)
  627. {
  628. $this->_AddNode($oNode);
  629. }
  630. $oIter2 = new RelationTypeIterator($oGraph, 'Edge');
  631. foreach($oIter2 as $oEdge)
  632. {
  633. $this->_AddEdge($oEdge);
  634. }
  635. }
  636. }
  637. /**
  638. * A simple iterator to "browse" the whole content of a graph,
  639. * either for only a given type of elements (Node | Edge) or for every type.
  640. */
  641. class RelationTypeIterator implements Iterator
  642. {
  643. protected $iCurrentIdx;
  644. protected $aList;
  645. /**
  646. * Constructor
  647. * @param SimpleGraph $oGraph The graph to browse
  648. * @param string $sType "Node", "Edge" or null
  649. */
  650. public function __construct(SimpleGraph $oGraph, $sType = null)
  651. {
  652. $this->iCurrentIdx = -1;
  653. $this->aList = array();
  654. switch($sType)
  655. {
  656. case 'Node':
  657. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  658. break;
  659. case 'Edge':
  660. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  661. break;
  662. default:
  663. foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
  664. foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
  665. }
  666. }
  667. public function rewind()
  668. {
  669. $this->iCurrentIdx = 0;
  670. }
  671. public function valid()
  672. {
  673. return array_key_exists($this->iCurrentIdx, $this->aList);
  674. }
  675. public function next()
  676. {
  677. $this->iCurrentIdx++;
  678. }
  679. public function current()
  680. {
  681. return $this->aList[$this->iCurrentIdx];
  682. }
  683. public function key()
  684. {
  685. return $this->iCurrentIdx;
  686. }
  687. }