lithium\analysis\Parser::match PHP Method

match() public static method

Token pattern matching.
public static match ( string $code, string $parameters, array $options = [] ) : array
$code string Source code to be analyzed.
$parameters string An array containing token patterns to be matched.
$options array The list of options to be used when matching `$code`: - 'ignore': An array of language tokens to ignore. - 'return': If set to 'content' returns an array of matching tokens.
return array Array of matching tokens.
    public static function match($code, $parameters, array $options = array())
    {
        $defaults = array('ignore' => array('T_WHITESPACE'), 'return' => true);
        $options += $defaults;
        $parameters = static::_prepareMatchParams($parameters);
        $tokens = is_array($code) ? $code : static::tokenize($code, $options);
        $results = array();
        foreach ($tokens as $i => $token) {
            if (!array_key_exists($token['name'], $parameters)) {
                if (!in_array('*', $parameters)) {
                    continue;
                }
            }
            $param = $parameters[$token['name']];
            if (isset($param['before']) && $i > 0) {
                if (!in_array($tokens[$i - 1]['name'], (array) $param['before'])) {
                    continue;
                }
            }
            if (isset($param['after']) && $i + 1 < count($tokens)) {
                if (!in_array($tokens[$i + 1]['name'], (array) $param['after'])) {
                    continue;
                }
            }
            $results[] = isset($token[$options['return']]) ? $token[$options['return']] : $token;
        }
        return $results;
    }

Usage Example

Ejemplo n.º 1
0
 public function testTokenPatternMatching()
 {
     $code = '$defaults = array("id" => "foo", "name" => "bar", \'count\' => 5);';
     $result = Parser::match($code, array('"string"'), array('return' => 'content'));
     $expected = array('"id"', '"foo"', '"name"', '"bar"', '\'count\'');
     $this->assertEqual($expected, $result);
     $result = Parser::match($code, array('"string"' => array('before' => '=>'), '1' => array('before' => '=>')), array('return' => 'content'));
     $expected = array('"foo"', '"bar"', '5');
     $this->assertEqual($expected, $result);
     $result = Parser::match($code, array('"string"' => array('after' => '=>')), array('return' => 'content'));
     $expected = array('"id"', '"name"', '\'count\'');
     $this->assertEqual($expected, $result);
 }