|
<?php |
|
|
|
use Finite\StateMachine\StateMachine; |
|
|
|
/** |
|
* The FiniteStateMachine Trait. |
|
* It provides easy ways to deal with Stateful objects and StateMachine |
|
* Prerequisite: install Finite package (https://github.com/yohang/Finite#readme) |
|
* Usage: in your Stateful Class, add the stateMachineConfig() protected method |
|
* and call initStateMachine() method at initialization (__contruct() method) |
|
* |
|
* @author Tortue Torche <[email protected]> |
|
*/ |
|
trait FiniteStateMachine |
|
{ |
|
/** |
|
* @var Finite\StateMachine\StateMachine |
|
*/ |
|
protected $stateMachine; |
|
|
|
/** |
|
* @var array |
|
*/ |
|
protected $finiteLoader; |
|
|
|
/** |
|
* @return array |
|
*/ |
|
protected abstract function stateMachineConfig(); |
|
|
|
public function initStateMachine() |
|
{ |
|
$this->finiteLoader = $this->stateMachineConfig(); |
|
$loader = new Finite\Loader\ArrayLoader($this->finiteLoader); |
|
$sm = new StateMachine($this); |
|
|
|
$loader->load($sm); |
|
|
|
$sm->initialize(); |
|
$this->stateMachine = $sm; |
|
} |
|
|
|
/** |
|
* Sets the object state |
|
* |
|
* @param string $state |
|
*/ |
|
public function setFiniteState($state) |
|
{ |
|
$this->state = $state; |
|
} |
|
|
|
/** |
|
* Get the object state |
|
* |
|
* @return string |
|
*/ |
|
public function getFiniteState() |
|
{ |
|
return $this->state; |
|
} |
|
|
|
/** |
|
* @return Finite\StateMachine\StateMachine |
|
*/ |
|
protected function getStateMachine() |
|
{ |
|
return $this->stateMachine; |
|
} |
|
|
|
/** |
|
* @return Finite\State\State |
|
*/ |
|
public function getCurrentState() |
|
{ |
|
return $this->getStateMachine()->getCurrentState(); |
|
} |
|
|
|
/** |
|
* @return string |
|
*/ |
|
public function getState() |
|
{ |
|
return $this->getCurrentState()->getName(); |
|
} |
|
|
|
/** |
|
* @return array<string> |
|
*/ |
|
public function getTransitions() |
|
{ |
|
return $this->getCurrentState()->getTransitions(); |
|
} |
|
|
|
/** |
|
* @return array<string> |
|
*/ |
|
public function getProperties() |
|
{ |
|
return $this->getCurrentState()->getProperties(); |
|
} |
|
|
|
/** |
|
* @param string $property |
|
* |
|
* @return bool |
|
*/ |
|
public function hasProperty($property) |
|
{ |
|
return $this->getCurrentState()->has($property); |
|
} |
|
|
|
/** |
|
* @param string $targetState |
|
* |
|
* @return bool |
|
*/ |
|
public function is($targetState) |
|
{ |
|
return $this->getState() === $targetState; |
|
} |
|
|
|
/** |
|
* @param string $transitionName |
|
* |
|
* @return bool |
|
*/ |
|
public function can($transitionName) |
|
{ |
|
return $this->getStateMachine()->can($transitionName); |
|
} |
|
|
|
/** |
|
* @param string $transitionName |
|
* |
|
* @return mixed |
|
* |
|
* @throws Finite\Exception\StateException |
|
*/ |
|
public function apply($transitionName) |
|
{ |
|
return $this->getStateMachine()->apply($transitionName); |
|
} |
|
|
|
} |