Finite_State_Machine.php 12 KB

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