izzum\statemachine\Transition::getRule PHP Method

getRule() public method

returns the associated Rule for this Transition, configured with a 'reference' (stateful) object
public getRule ( Context $context ) : izzum\rules\IRule
$context Context the associated Context for a our statemachine
return izzum\rules\IRule a Rule or chained AndRule if the rule input was a ',' seperated string of rules.
    public function getRule(Context $context)
    {
        // if no rule is defined, just allow the transition by default
        if ($this->rule === '' || $this->rule === null) {
            return new TrueRule();
        }
        $entity = $context->getEntity();
        // a rule string can be made up of multiple rules seperated by a comma
        $all_rules = explode(',', $this->rule);
        $rule = new TrueRule();
        foreach ($all_rules as $single_rule) {
            // guard clause to check if rule exists
            if (!class_exists($single_rule)) {
                $e = new Exception(sprintf("failed rule creation, class does not exist: (%s) for Context (%s).", $this->rule, $context->toString()), Exception::RULE_CREATION_FAILURE);
                throw $e;
            }
            try {
                $and_rule = new $single_rule($entity);
                // create a chain of rules that need to be true
                $rule = new AndRule($rule, $and_rule);
            } catch (\Exception $e) {
                $e = new Exception(sprintf("failed rule creation, class objects to construction with entity: (%s) for Context (%s). message: %s", $this->rule, $context->toString(), $e->getMessage()), Exception::RULE_CREATION_FAILURE);
                throw $e;
            }
        }
        return $rule;
    }

Usage Example

 /**
  * @test
  */
 public function shouldExpectExceptionsWhenCallingPublicMethodsWithNonDefaultConstructorValues()
 {
     $from = new State('a');
     $to = new State('b');
     $rule = 'izzum\\rules\\BOGUS';
     $command = 'izzum\\command\\BOGUS';
     $object = new Context(new Identifier(Identifier::NULL_ENTITY_ID, Identifier::NULL_STATEMACHINE));
     $transition = new Transition($from, $to, null, $rule, $command);
     $this->assertEquals($from . '_to_' . $to, $transition->getName());
     $this->assertEquals($from, $transition->getStateFrom());
     $this->assertEquals($to, $transition->getStateTo());
     $this->assertContains($transition->getName(), $transition->toString());
     try {
         $command = $transition->getCommand($object);
         $this->fail('should not come here');
     } catch (Exception $e) {
         $this->assertEquals(Exception::COMMAND_CREATION_FAILURE, $e->getCode());
     }
     try {
         $rule = $transition->getRule($object);
         $this->fail('should not come here');
     } catch (Exception $e) {
         $this->assertEquals(Exception::RULE_CREATION_FAILURE, $e->getCode());
     }
 }