PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

APPENDIX B ■ A SIMPLE PARSER


}


class EqualsHandler implements \gi\parse\Handler {
function handleMatch( \gi\parse\Parser $parser, \gi\parse\Scanner $scanner ) {
$comp1 = $scanner->getContext()->popResult();
$comp2 = $scanner->getContext()->popResult();
$scanner->getContext()->pushResult(
new EqualsExpression( $comp1, $comp2 ) );
}
}


class BooleanOrHandler implements \gi\parse\Handler {
function handleMatch( \gi\parse\Parser $parser, \gi\parse\Scanner $scanner ) {
$comp1 = $scanner->getContext()->popResult();
$comp2 = $scanner->getContext()->popResult();
$scanner->getContext()->pushResult(
new BooleanOrExpression( $comp1, $comp2 ) );
}
}


class BooleanAndHandler implements \gi\parse\Handler {
function handleMatch( \gi\parse\Parser $parser, \gi\parse\Scanner $scanner ) {
$comp1 = $scanner->getContext()->popResult();
$comp2 = $scanner->getContext()->popResult();
$scanner->getContext()->pushResult(
new BooleanAndExpression( $comp1, $comp2 ) );
}
}


Bearing in mind that you also need the Interpreter example from Chapter 11 at hand, you can work
with the MarkParse class like this:


$input = 'five';
$statement = "( \$input equals 'five')";


$engine = new MarkParse( $statement );
$result = $engine->evaluate( $input );
print "input: $input evaluating: $statement\n";
if ( $result ) {
print "true!\n";
} else {
print "false!\n";
}


This should produce the following results:

input: five evaluating: ( $input equals 'five')
true!

Free download pdf