Skip to content

Instantly share code, notes, and snippets.

@nb
Created May 4, 2010 23:44
Show Gist options
  • Save nb/390201 to your computer and use it in GitHub Desktop.
Save nb/390201 to your computer and use it in GitHub Desktop.
<?php
require_once 'PHPUnit/Framework.php';
/**
* Matches a php code string upon a template of tokens
*
* @param string $code String of php code.
* @param string $template See the tests below for examples.
*
* @return array|false Associative array of all variables or false if no match was found
*/
function php_code_token_match( $code, $template ) {
$vars = array();
$tokens = token_get_all( $code );
$are_tokens_equal = create_function( '$t1, $t2', 'return ( $t1 == $t2 ) || ( is_array( $t1 ) && is_array( $t2 ) && $t1[0] == $t2[0] && $t1[1] == $t2[1] );' );
$real_template = $template;
while ( $tokens ) {
$sub_tokens = $tokens;
$found = true;
$template = $real_template;
while( $template ) {
$token = array_shift( $sub_tokens );
if ( is_null( $token ) ) {
$found = false;
break;
}
if ( is_array( $token) && $token[0] == T_WHITESPACE ) {
continue;
}
$template_token = array_shift( $template );
if ( is_null( $template_token ) ) {
break;
}
if ( is_string( $template_token ) && $template_token[0] == '?' ) {
$vars[substr( $template_token, 1 )] = is_array( $token )? $token[1] : $token;
} elseif ( !$are_tokens_equal( $token, $template_token ) ) {
$found = false;
break;
}
}
if ( $found ) return $vars;
array_shift( $tokens );
}
return false;
}
class PHPCodeTokenMatchTest extends PHPUnit_Framework_TestCase {
function test_string_token() {
$this->assertEquals( array(), php_code_token_match( '<?php $baba = 5;?>', array('=') ) );
}
function test_string_and_placeholder() {
$this->assertEquals( array('var' => 5), php_code_token_match( '<?php $baba = 5;?>', array('=', '?var') ) );
}
function test_array_token() {
$this->assertEquals( array( 'x' => '"baba"'), php_code_token_match( '<?php $var = "baba"; ?>', array( array( T_VARIABLE, '$var'), '=', '?x' ) ) );
}
function test_not_found() {
$this->assertEquals( false, php_code_token_match( '<?php $var "baba"; ?>', array( array( T_VARIABLE, '$var'), '=', '?x' ) ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment