izzum\statemachine\utils\Utils::matchesRegex PHP Method

matchesRegex() public static method

does an input regex state match a target states' name?
public static matchesRegex ( State $regex, State $target ) : boolean
$regex izzum\statemachine\State the regex state
$target izzum\statemachine\State the state to match the regular expression to
return boolean
    public static function matchesRegex(State $regex, State $target)
    {
        $matches = false;
        if ($regex->isNormalRegex()) {
            $expression = str_replace(State::REGEX_PREFIX, '', $regex->getName());
            $matches = preg_match($expression, $target->getName()) === 1;
        }
        if ($regex->isNegatedRegex()) {
            $expression = str_replace(State::REGEX_PREFIX_NEGATED, '', $regex->getName());
            $matches = preg_match($expression, $target->getName()) !== 1;
        }
        return $matches;
    }

Usage Example

 /**
  * @test
  * @group regex
  */
 public function shouldMatchValidRegexAndNegatedRegex()
 {
     $name = 'regex:/.*/';
     //only allow regexes between regex begin and end markers
     $regex = new State($name);
     $target = new State('aa');
     $this->assertTrue(Utils::matchesRegex($regex, $target), 'only allow regexes between regex begin and end markers');
     $name = 'regex:/a|b/';
     //allow regexes without regex begin and end markers
     $regex = new State($name);
     $target = new State('b');
     $this->assertTrue(Utils::matchesRegex($regex, $target));
     $name = 'regex:/c|a|aa/';
     $regex = new State($name);
     $target = new State('aa');
     $this->assertTrue(Utils::matchesRegex($regex, $target));
     $name = 'regex:/action-.*/';
     $regex = new State($name);
     $target = new State('action-hero');
     $bad = new State('action_hero');
     $this->assertTrue(Utils::matchesRegex($regex, $target));
     $this->assertFalse(Utils::matchesRegex($regex, $bad));
     $name = 'regex:/go[o,l]d/';
     $regex = new State($name);
     $target = new State('gold');
     $bad = new State('golld');
     $this->assertTrue(Utils::matchesRegex($regex, $target));
     $this->assertFalse(Utils::matchesRegex($regex, $bad));
     //NOT matching a regex
     $name = 'not-regex:/go[o,l]d/';
     $regex = new State($name);
     $target = new State('goad');
     $bad = new State('gold');
     $this->assertTrue(Utils::matchesRegex($regex, $target));
     $this->assertFalse(Utils::matchesRegex($regex, $bad));
 }