Finite_State_Machine.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. /**
  3. * Finite state machine skeleton
  4. *
  5. * @copyright (c) 2007 OSI
  6. * @author Frédéric G. MARAND
  7. * @license Licensed under the CeCILL 2.0
  8. * @version CVS: $Id: Finite_State_Machine.php,v 1.8 2007-06-10 16:30:30 marand Exp $
  9. * @link http://wiki.audean.com/fsm/fsm
  10. * @since Not applicable yet
  11. * @package fsm
  12. * @subpackage fsm.core
  13. * @todo replace setAttribute('id',...) by setIdAttribute when PHP5.2 becomes mandatory
  14. */
  15. require_once('misc.php'); // for func_name()
  16. $erFiniteStateMachine = error_reporting(E_ALL|E_STRICT);
  17. /**
  18. * This class defines a possible outcome for a given FSM transition
  19. *
  20. */
  21. class Fsm_Result
  22. {
  23. /**
  24. * The return value of the event handler
  25. * @var mixed
  26. */
  27. public $fsm_return;
  28. /**
  29. * The name of the state to which the FSM must change. If NULL, do not change
  30. * the current state.
  31. *
  32. * @var string
  33. */
  34. public $fsm_state;
  35. /**
  36. * The name of an event to be fired after the state change has been applied
  37. *
  38. * @var string
  39. */
  40. public $fsm_action;
  41. /**
  42. * @param string $state
  43. * @param string $action
  44. * @return void
  45. */
  46. public function __construct($return = NULL, $state = NULL, $action = NULL)
  47. {
  48. $this->fsm_return = $return;
  49. $this->fsm_state = $state;
  50. $this->fsm_action = $action;
  51. }
  52. }
  53. /**
  54. * This class must be inherited by code implementing actual FSMs.
  55. *
  56. * Applications must create a fsm descendant in which they will:
  57. *
  58. * - define the f_transitions table, usually in their constructor
  59. * - invoke the parent constructor to set up the FSM from the transitions table
  60. * - create "f_foo" functions for each "foo" event, except "idle", which is builtin.
  61. *
  62. * Applications may:
  63. * - disable event processing by setting $this->event to one of the fsm::EVENT_* constants
  64. * - disable post-event actions by setting $this->allows actions to false
  65. * - disable the builtin idle event by setting $this->idle_work to false
  66. * - query the current state by using $this->get_state()
  67. * - send an idle event by using $this->idle()
  68. * - submit any event (including idle) by using $this->apply_event($event_name)
  69. *
  70. */
  71. abstract class Finite_State_Machine
  72. {
  73. const VERSION = '$Id';
  74. const IDLE_EVENT = 'idle'; // must not change name: method f_idle depends on it
  75. const INIT_STATE = 'init';
  76. const FINAL_STATE = 'final';
  77. const EVENT_NORMAL = 1; // processes events
  78. const EVENT_QUEUE = 2; // queue events for later use
  79. const EVENT_SINK = 3; // throw away events
  80. public $idle_work = TRUE;
  81. public $allow_actions = TRUE;
  82. protected $f_event_mode = Finite_State_Machine::EVENT_NORMAL;
  83. protected $f_queue = array(); // event queue for EVENT_QUEUE mode
  84. /**
  85. * the current state of the object
  86. * @var string
  87. */
  88. protected $f_state;
  89. /**
  90. * Transitions holds the transitions table
  91. * state1
  92. * event1
  93. * result1
  94. * state_name|Fsm_Result
  95. * event2
  96. * ...
  97. * ..
  98. * ..
  99. * @var array
  100. */
  101. protected $f_transitions = null;
  102. /**
  103. * constructor initializes the FSM to the first
  104. * state in the transitions table
  105. * @return void
  106. */
  107. public function __construct()
  108. {
  109. $this->_check_transitions();
  110. reset($this->f_transitions);
  111. $x = each($this->f_transitions);
  112. $x = $x[0];
  113. $this->f_state = $x;
  114. }
  115. /**
  116. * make sure a transitions graph has been defined
  117. * @return void
  118. */
  119. protected function _check_transitions()
  120. {
  121. if (!isset($this->f_transitions))
  122. throw new Exception('No FSM processing is allowed without a transitions table\n');
  123. }
  124. /**
  125. * getter for f_state
  126. * @return string
  127. */
  128. public function get_state()
  129. {
  130. return $this->f_state;
  131. }
  132. /**
  133. * return the list of events accepted in the current state
  134. * @return array
  135. */
  136. public function get_accepted_events()
  137. {
  138. $this->_check_transitions();
  139. try
  140. {
  141. $events = array_keys($this->f_transitions[$this->f_state]);
  142. // echo func_name() . ": state $this->f_state, accepted events are:\n" . print_r($events, true). "\n";
  143. }
  144. catch (Exception $e)
  145. {
  146. echo "Exception in get_accepted_events" . print_r($e);
  147. print_r(debug_backtrace());
  148. $events = array();
  149. }
  150. return $events;
  151. }
  152. /**
  153. * return the list of outcome accepted in the current state for the give event
  154. * @param string $event_name
  155. * @param mixed $outcome
  156. * @return array
  157. */
  158. public function get_accepted_outcomes($event_name)
  159. {
  160. // echo func_name() . "\n";
  161. $this->_check_transitions();
  162. /**
  163. * Spare some paranioa
  164. *
  165. if (!$this->is_event_allowed($event_name))
  166. throw new Exception(func_name() . ": event \"$event_name\" not allowed in state \"$this->f_state\"\n");
  167. */
  168. $outcomes = array_keys($this->f_transitions[$this->f_state][$event_name]);
  169. // print_r($this->f_transitions[$this->f_state][$event_name]);
  170. // echo "outcomes for event $event_name: " . var_dump($outcomes) . "\n";
  171. return $outcomes;
  172. }
  173. /**
  174. * is this event accepted in the current state
  175. * the FSM is in ?
  176. *
  177. * @param string $event_name
  178. * @return boolean
  179. */
  180. public function is_event_allowed($event_name)
  181. {
  182. // echo func_name() . "($event_name)";
  183. $this->_check_transitions();
  184. $ret = in_array($event_name, $this->get_accepted_events());
  185. // echo " in state $this->f_state, result = <$ret>\n";
  186. return $ret;
  187. }
  188. /**
  189. * is a given outcome available for a given event,
  190. * considering the current context ?
  191. *
  192. * @param string $event_name
  193. * @param mixed $outcome
  194. * @return boolean
  195. */
  196. public function is_outcome_allowed($event_name, $outcome)
  197. {
  198. $this->_check_transitions();
  199. if (!$this->is_event_allowed($event_name))
  200. return false;
  201. $ret = array_key_exists($outcome, $this->get_accepted_outcomes($event_name));
  202. return $ret;
  203. }
  204. /**
  205. * apply an event, and the resulting event chain if needed
  206. *
  207. * @param string $event_name
  208. * @param array $params the
  209. * @return Fsm_Result resulting state
  210. */
  211. public function apply_event($event_name)
  212. {
  213. // echo "Start of " . func_name() . "\n";
  214. do {
  215. $result = $this->apply_simple_event($event_name);
  216. if ($this->allow_actions)
  217. {
  218. $event_name = $result->fsm_action; // can be NULL
  219. }
  220. else
  221. {
  222. $event_name = NULL;
  223. }
  224. } while($event_name);
  225. // echo "End of " . func_name() . "\n";
  226. return $result;
  227. }
  228. /**
  229. * Helper for apply_event that does not implement the post-transition action
  230. *
  231. * @param string $event_name
  232. * @return Fsm_Result
  233. * @see apply_event()
  234. */
  235. private function apply_simple_event($event_name)
  236. {
  237. // echo "Start of " . func_name() . ", event = $event_name\n";
  238. $current_state = $this->f_state;
  239. if (($event_name == Finite_State_Machine::IDLE_EVENT) && !$this->idle_work)
  240. {
  241. return new Fsm_Result();
  242. }
  243. if (!$this->is_event_allowed($event_name))
  244. {
  245. die("Event $event_name not allowed in current state $current_state.\n");
  246. /* throw new Exception(func_name()
  247. . ": Event \"$event_name\" not accepted in current state \"$current_state\"");
  248. */
  249. }
  250. $outcomes = $this->get_accepted_outcomes($event_name);
  251. $method_name = "event$event_name";
  252. if (!method_exists($this, $method_name))
  253. {
  254. die (func_name() . ": missing method "
  255. . get_class($this) . "::$method_name. Aborting.\n");
  256. }
  257. $outcome = $this->$method_name();
  258. if (!in_array($outcome, $outcomes))
  259. {
  260. throw new Exception(func_name()
  261. . ": event guard. Transition on \"$event_name\" return invalid outcome: "
  262. . print_r($outcome, true)
  263. . " for state $this->f_state\n");
  264. }
  265. $transition = &$this->f_transitions[$current_state][$event_name][$outcome];
  266. $result = new Fsm_Result
  267. (
  268. $outcome,
  269. $transition[0],
  270. $transition[1]
  271. );
  272. if (isset($result->fsm_state))
  273. {
  274. $this->f_state = $result->fsm_state;
  275. }
  276. /* print_r($this->f_transitions[$current_state][$event_name]);
  277. var_dump($result); */
  278. if (!isset($outcome))
  279. $outcome = 'NULL';
  280. /*
  281. echo func_name()
  282. . ": $current_state: " . $event_name . '[' . $outcome . ']'
  283. . " -> $this->f_state / " . $result->fsm_action . PHP_EOL;
  284. */
  285. return $result;
  286. }
  287. /**
  288. * Default event
  289. * @return boolean
  290. */
  291. public function f_idle()
  292. {
  293. return TRUE;
  294. }
  295. /**
  296. * Apply an fsm::IDLE_EVENT event. Do not confuse with f_idle !
  297. *
  298. * @return Fsm_Result
  299. */
  300. public function idle()
  301. {
  302. return $this->apply_event(Finite_State_Machine::IDLE_EVENT);
  303. }
  304. /**
  305. * return the current operating mode of the FSM
  306. * @return int
  307. */
  308. public function get_event_mode()
  309. {
  310. return $this->f_event_mode;
  311. }
  312. /**
  313. * set the current operating mode for the FSM
  314. *
  315. * @param int $mode fsm::EVENT_* constants
  316. * @return int $mode fsm::EVENT_* constants
  317. */
  318. public function set_event_mode($mode)
  319. {
  320. switch ($mode)
  321. {
  322. case Finite_State_Machine::EVENT_NORMAL :
  323. if (count($this->f_queue) > 0)
  324. {
  325. while (($event = array_shift($this->f_queue)) !== NULL)
  326. {
  327. $this->apply_event($event);
  328. }
  329. }
  330. break;
  331. case Finite_State_Machine::EVENT_QUEUE : // nothing special to do
  332. break;
  333. case Finite_State_Machine::EVENT_SINK : // empty queue if needed
  334. if (count($this->f_queue) > 0)
  335. {
  336. $this->f_queue = array();
  337. }
  338. break;
  339. default:
  340. throw new Exception("Trying to set unknown FSM mode $mode");
  341. }
  342. $this->f_event_mode = $mode;
  343. return $this->f_event_mode;
  344. }
  345. /**
  346. * Load the f_transitions table from an external resource.
  347. *
  348. * @param string $url Optional: defaults to the name of the class, . ".xml"
  349. */
  350. public function load_fsm($url = NULL)
  351. {
  352. $osd = FALSE; // on screen display (debug)
  353. if ($osd)
  354. echo "Loading FSM from $url\n";
  355. if (!isset($url))
  356. {
  357. $url = get_class($this) . ".xml";
  358. }
  359. $fsm = simplexml_load_file($url);
  360. $fsm_version = (string) $fsm['fsm_version'];
  361. if ($fsm_version !== '1.3')
  362. {
  363. die("Revision $fsm_version of schema is not supported.\n");
  364. }
  365. $this->idle_work = ($fsm['idle_work'] == 1);
  366. $this->allow_actions = ($fsm['allow_actions'] == 1);
  367. $this->f_transitions = array();
  368. $t = &$this->f_transitions;
  369. // (string) casts in this loop are required: RHS is a SimpleXMLElement
  370. foreach ($fsm->state as $state)
  371. {
  372. $id = (string) $state['id'];
  373. if ($osd)
  374. echo "State $id :\n";
  375. $t[$id] = array();
  376. switch ($id)
  377. {
  378. case Finite_State_Machine::INIT_STATE :
  379. if ($osd)
  380. echo " Initial state\n";
  381. break;
  382. case Finite_State_Machine::FINAL_STATE :
  383. if ($osd)
  384. echo " Final state\n";
  385. break;
  386. }
  387. foreach ($state->event as $event)
  388. {
  389. $ename = (string) $event['name'];
  390. if ($osd)
  391. echo " Event $ename";
  392. if (!isset($event['type']))
  393. $event['type'] = 'void';
  394. $etype = (string) $event['type'];
  395. if ($osd)
  396. echo ", type $etype\n";
  397. foreach ($event as $next)
  398. {
  399. if ($event['type'] == 'void')
  400. {
  401. $next['result'] = 'always';
  402. $eresult = null;
  403. }
  404. else
  405. $eresult = (string) $next['result'];
  406. if (!isset($next['state']))
  407. $next['state'] = (string) $state['id'];
  408. if ($osd)
  409. {
  410. echo " Next(" . $next['result'] . ') = ' . $next['state'];
  411. if (isset($next['action']))
  412. echo " + event " . $next['action'];
  413. echo PHP_EOL;
  414. }
  415. $t[$id][$ename][$eresult] = array(
  416. (string) $next['state'],
  417. (string) $next['action']);
  418. }
  419. }
  420. }
  421. }
  422. }
  423. error_reporting($erFiniteStateMachine);
  424. unset($erFiniteStateMachine);