Writer.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. /**
  3. * Finite state machine writer.
  4. *
  5. * Keeping the FSM writer (generation) functions out of the root class minimizes
  6. * the code volume for FSM readers, which should represent the majority of FSM
  7. * users.
  8. *
  9. * @copyright (c) 2007-2012 Ouest Systèmes Informatiques
  10. * @author Frédéric G. MARAND
  11. * @license Licensed under the CeCILL 2.0
  12. * @link http://wiki.audean.com/fsm/fsm
  13. */
  14. namespace Osinet\FiniteStateMachine;
  15. /**
  16. * Needed notably for func_name()
  17. */
  18. require_once('misc.php');
  19. $erFiniteStateMachine = error_reporting(E_ALL|E_STRICT);
  20. /**
  21. * Read/Write concrete FSM class.
  22. *
  23. * This (concrete) class extends the default abstract FiniteStateMachine to
  24. * add write behaviours. It is to be used by applications wishing to write FSM
  25. * files. Other applications should not use it to avoid code bloat.
  26. */
  27. class Writer extends Machine {
  28. const FORMAT_VERSION = '1.1';
  29. public function __construct() {
  30. $this->fTransitions = array();
  31. parent::__construct();
  32. }
  33. /**
  34. * Return the initial and final states from an abstract FSM graph.
  35. *
  36. * @param array $graph
  37. * A concrete FSM derived from the abstract FSM.
  38. *
  39. * @return array
  40. */
  41. protected function getSpecialStates($graph) {
  42. $ret = array(NULL, NULL);
  43. foreach ($graph['states'] as $state) {
  44. if (isset($state['type']) && $state['type'] == 'initial') {
  45. $ret[0] = $state['name'];
  46. }
  47. if (isset($state['type']) && $state['type'] == 'final') {
  48. $ret[1] = $state['name'];
  49. }
  50. if (isset($ret[0]) && isset($ret[1])) {
  51. break;
  52. }
  53. }
  54. return $ret;
  55. }
  56. /**
  57. * Return the transitions (triggers) available from a given state
  58. *
  59. * @param array $graph
  60. * A concrete Machine.
  61. * @param string $id
  62. * State id in the abstract graph (not id in the XML FSM).
  63. *
  64. * @return array
  65. */
  66. protected function getTransitionsForState($graph, $id) {
  67. $ret = array();
  68. foreach ($graph['transitions'] as $txid => $transition) {
  69. // echo "id = $id, txid = $txid from = " . $transition['from'] . PHP_EOL;
  70. if ($transition['from'] == $id) {
  71. $ret[] = $txid;
  72. }
  73. }
  74. return $ret;
  75. }
  76. /**
  77. * Generate the XML FSM file and optionally PHP stubs file.
  78. *
  79. * Source is an abstract FSM representation as an array of states/transitions.
  80. *
  81. * @param array $graph
  82. * @param string $prefix
  83. * @param boolean $php
  84. * @param boolean $overwrite
  85. *
  86. * @todo take $overwrite and $php into account
  87. *
  88. * @deprecated
  89. */
  90. public function oldSaveFsm($graph, $prefix = 'fsm', $php = FALSE, $overwrite = FALSE) {
  91. echo "This is a dump for FSM $prefix"
  92. . ', ' . ($php ? 'with' : 'without') . ' PHP generation'
  93. . ', ' . ($overwrite ? 'with' : 'without') . ' overwrite mode'
  94. . ".\n";
  95. $doc = new \DOMDocument('1.0', 'utf-8');
  96. $comment = new \DOMComment(' Generated by '
  97. . basename(__FILE__, '.php')
  98. . " version " . Fsm_Writer::VERSION
  99. . " ");
  100. $doc->appendChild($comment);
  101. $fsm = new \DOMElement('fsm');
  102. $doc->appendChild($fsm);
  103. $fsm->setAttribute('fsm_version', "1.3");
  104. $fsm->setAttribute('idle_work', "1");
  105. $fsm->setAttribute('allow_actions', "1");
  106. list($init, $final) = $this->getSpecialStates($graph);
  107. $fsm->setAttribute('init', $init);
  108. $fsm->setAttribute('final', $final);
  109. foreach ($graph['states'] as $id => $state) {
  110. $state_node = new \DOMElement('state');
  111. $fsm->appendChild($state_node);
  112. $state_node->setIdAttribute('id', $state['name']);
  113. $transitions = $this->getTransitionsForState($graph, $id);
  114. /**
  115. * FGM on ne peut pas simplement boucler ainsi: on a dans le graphe
  116. * abstrait une transition par évènement, alors que dans la FSM les
  117. * transitions partant du même état sont groupées. En se contentant
  118. * de boucler ainsi, on crée un "event" pour chaque transition alors
  119. * qu'il faut créer 1 event et "n" next.
  120. */
  121. foreach ($transitions as $transition_id) {
  122. $event_node = new \DOMElement('event');
  123. $state_node->appendChild($event_node);
  124. $transition = $graph['transitions'][$transition_id];
  125. $event_node->setAttribute('name', $transition['trigger']);
  126. /**
  127. * @todo support other event types
  128. */
  129. $event_node->setAttribute('type', 'string');
  130. }
  131. }
  132. $doc->save("$prefix.xml");
  133. print_r($graph['transitions']);
  134. }
  135. /**
  136. * Add a new state to the transitions table.
  137. *
  138. * @param string $name
  139. *
  140. * @return integer 0 on success, < 0 on failure
  141. */
  142. public function addState($name) {
  143. // echo func_name() . "($name)";
  144. if (array_key_exists($name, $this->fTransitions)) {
  145. $ret = -1;
  146. }
  147. else {
  148. $this->fTransitions[$name] = array();
  149. $ret = 0;
  150. }
  151. // echo ", ret = $ret\n";
  152. return $ret;
  153. }
  154. /**
  155. * Add an event definition (name + optional type of handler) to an existing state
  156. *
  157. * @param string $state
  158. * @param string $event
  159. * @param string $type
  160. *
  161. * @return integer
  162. * - 0 on success
  163. * - < 0 on failure
  164. */
  165. public function addEvent($state, $event, $type = 'string') {
  166. if (!array_key_exists($state, $this->fTransitions)) {
  167. $ret = -1;
  168. }
  169. elseif (array_key_exists($event, $this->fTransitions[$state])) {
  170. $ret = -2;
  171. }
  172. // state exists, event doesn't: OK
  173. else {
  174. $this->fTransitions[$state][$event] = array();
  175. $this->fTransitions[$state][$event]["#type"] = $type;
  176. $ret = 0;
  177. }
  178. return $ret;
  179. }
  180. /**
  181. * Add an outcome definition to an existing event:
  182. * - event handler result
  183. * - next state
  184. * - event to fire after transition to next state
  185. * All outcome fields are optional
  186. *
  187. * @param name $state
  188. * @param name $event
  189. *
  190. * @return integer
  191. * - 0 on success
  192. * - < 0 on failure
  193. */
  194. public function addOutcome($state, $event,
  195. $result = NULL, // if null, single possible outcome; only possible on void events
  196. $next_state = NULL, // if null, stay on same state
  197. $action = NULL) // if null, do not send an event after transitioning
  198. {
  199. $t = &$this->fTransitions;
  200. if (!array_key_exists($state, $t)) {
  201. $ret = -1;
  202. }
  203. elseif (!array_key_exists($event, $t[$state])) {
  204. $ret = -2;
  205. }
  206. elseif (($result == NULL) && ($t[$state][$event]['#type'] <> 'void')) {
  207. $ret = -3; // Undefined, single, results are only available for void events
  208. }
  209. elseif (($result != NULL) && array_key_exists($result, $t[$state][$event])) {
  210. $ret = -4; // results must be unique per event
  211. }
  212. else {
  213. $t[$state][$event][$result] = array($next_state, $action);
  214. $ret = 0;
  215. }
  216. return $ret;
  217. }
  218. /**
  219. * Defines the special states in the FSM
  220. *
  221. * @param string $kind FiniteStateMachine::INIT_STATE or ..FINAL_STATE
  222. * @param string $name
  223. */
  224. public function setSpecialState($kind, $name) {
  225. // echo func_name() . "($kind, $name)\n";
  226. if (($kind != Machine::INIT_STATE) && ($kind != Machine::FINAL_STATE)) {
  227. $ret = -1; // unknown special state
  228. }
  229. elseif (!array_key_exists($name, $this->fTransitions)) {
  230. $ret = -2; // non existent state declared as special
  231. }
  232. else {
  233. $this->fTransitions["#$kind"] = $name;
  234. $ret = 0;
  235. }
  236. return $ret;
  237. }
  238. /*
  239. * Generate the XML FSM file and optionally PHP stubs file.
  240. *
  241. * Source is a valid instance of FSM.
  242. *
  243. * @param string $prefix
  244. * @param boolean $php
  245. * @param boolean $overwrite
  246. *
  247. * @todo take $overwrite and $php into account
  248. *
  249. * @throws Exception from within checkTransitions
  250. */
  251. public function saveFsm($prefix = 'fsm', $php = FALSE, $overwrite = FALSE) {
  252. $this->checkTransitions();
  253. $t = &$this->fTransitions;
  254. echo "This is a dump for FSM $prefix"
  255. . ', ' . ($php ? 'with' : 'without') . ' PHP generation'
  256. . ', ' . ($overwrite ? 'with' : 'without') . ' overwrite mode'
  257. . ".\n";
  258. $doc = new \DOMDocument('1.0', 'utf-8');
  259. $comment = new \DOMComment(' Generated by '
  260. . basename(__FILE__, '.php')
  261. . " version " . Writer::FORMAT_VERSION
  262. . " on FSM version " . Machine::VERSION
  263. . " ");
  264. $doc->appendChild($comment);
  265. $fsm = new \DOMElement('fsm');
  266. $doc->appendChild($fsm);
  267. $fsm->setAttribute('fsm_version', "1.3");
  268. $fsm->setAttribute('idle_work', "1");
  269. $fsm->setAttribute('allow_actions', "1");
  270. $fsm->setAttribute('init', $t['#' . Machine::INIT_STATE]);
  271. $fsm->setAttribute('final', $t['#' . Machine::FINAL_STATE]);
  272. foreach ($this->fTransitions as $stateName => $state) {
  273. if ($stateName[0] == '#') {
  274. continue; // ignore special state definitions
  275. }
  276. $stateNode = new \DOMElement('state', "\n");
  277. $fsm->appendChild($stateNode);
  278. $stateNode->setIdAttribute('id', $stateName);
  279. foreach ($state as $eventName => $event) {
  280. $eventNode = new \DOMElement('event', "\n");
  281. $stateNode->appendChild($eventNode);
  282. $eventNode->setAttribute('name', $eventName);
  283. $eventNode->setAttribute('type', $event['#type']);
  284. foreach ($event as $outcomeName => $outcome) {
  285. if ($outcomeName[0] == '#') {
  286. continue; // ignore special outcome definitions (event type)
  287. }
  288. $outcomeNode = new \DOMElement('next', "\n");
  289. $eventNode->appendChild($outcomeNode);
  290. /**
  291. * Generated FSMs currently always use the "string" event handler type,
  292. * meaning they always have outcome results. This will not always be
  293. * the case, hence this test (think ftp.xml)
  294. */
  295. if (!empty($outcomeName)) {
  296. $outcomeNode->setAttribute('result', $outcomeName);
  297. }
  298. if (!empty($outcome[0])) {
  299. $outcomeNode->setAttribute('state', $outcome[0]);
  300. }
  301. if (!empty($outcome[1])) {
  302. $outcomeNode->setAttribute('action', $outcome[1]);
  303. }
  304. }
  305. }
  306. }
  307. $doc->save("$prefix.xml");
  308. }
  309. }