PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

■Appendix B: A Simple Parser ............................................................................


protected $token = null;
protected $token_type = -1;
// Reader provides access to the raw character data. Context stores
// result data
function __construct( Reader $r, Context $context ) {
$this->r = $r;
$this->context = $context;
}


function getContext() {
return $this->context;
}


// read through all whitespace characters
function eatWhiteSpace( ) {
$ret = 0;
if ( $this->token_type != self::WHITESPACE &&
$this->token_type != self::EOL ) {
return $ret;
}
while ( $this->nextToken() == self::WHITESPACE ||
$this->token_type == self::EOL ) {
$ret++;
}
return $ret;
}


// get a string representation of a token
// either the current token, or that represented
// by the $int arg
function getTypeString( $int=-1 ) {
if ( $int<0 ) { $int=$this->tokenType(); }
if ( $int<0 ) { return null; }
$resolve = array(
self::WORD => 'WORD',
self::QUOTE => 'QUOTE',
self::APOS => 'APOS',
self::WHITESPACE => 'WHITESPACE',
self::EOL => 'EOL',
self::CHAR => 'CHAR',
self::EOF => 'EOF' );
return $resolve[$int];
}


// the current token type (represented by an integer)
function tokenType() {
return $this->token_type;
}


// get the contents of the current token
function token() {
return $this->token;
}

Free download pdf