Source for file parser.php
Documentation is available at parser.php
* base include file for SimpleTest
* @subpackage MockObjects
* @version $Id: parser.php 1723 2008-04-08 00:34:10Z lastcraft $
* Lexer mode stack constants
foreach (array('LEXER_ENTER', 'LEXER_MATCHED',
'LEXER_UNMATCHED', 'LEXER_EXIT',
'LEXER_SPECIAL') as $i =>
$constant) {
* Compounded regular expression. Any of
* the contained patterns could match and
* when one does, it's label is returned.
* Constructor. Starts with no patterns.
* @param boolean $case True for case sensitive, false
* Adds a pattern with an optional label.
* @param string $pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string $label Label of regex to be returned
* Attempts to match all patterns at once against
* @param string $subject String to match against.
* @param string $match First matched portion of
* @return boolean True on success.
function match($subject, &$match) {
if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) {
for ($i =
1; $i <
count($matches); $i++
) {
* Compounds the patterns into a single
* regular expression separated with the
* "or" operator. Caches the regex.
* Will automatically escape (, ) and / tokens.
* @param array $patterns List of patterns in order.
function _getCompoundedRegex() {
* Accessor for perl regex mode flags to use.
* @return string Perl regex flags.
function _getPerlMatchingFlags() {
return ($this->_case ?
"msS" :
"msSi");
* States for a stack machine.
* Constructor. Starts in named state.
* @param string $start Starting state name.
$this->_stack =
array($start);
* Accessor for current state.
* Adds a state to the stack and sets it
* to be the current state.
* @param string $state New state.
* Leaves the current state and reverts
* @return boolean False if we drop off
* the bottom of the list.
* Accepts text and breaks it into tokens.
* Some optimisation to make the sure the
* content is only scanned by the PHP regex
* parser once. Lexer modes must not start
* with leading underscores.
* Sets up the lexer in case insensitive matching
* @param SimpleSaxParser $parser Handling strategy by
* @param string $start Starting handler.
* @param boolean $case True for case sensitive.
function SimpleLexer(&$parser, $start =
"accept", $case =
false) {
* Adds a token search pattern for a particular
* parsing mode. The pattern does not change the
* @param string $pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string $mode Should only apply this
* pattern when dealing with
$this->_regexes[$mode]->addPattern($pattern);
* Adds a pattern that will enter a new parsing
* mode. Useful for entering parenthesis, strings,
* @param string $pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string $mode Should only apply this
* pattern when dealing with
* @param string $new_mode Change parsing to this new
$this->_regexes[$mode]->addPattern($pattern, $new_mode);
* Adds a pattern that will exit the current mode
* and re-enter the previous one.
* @param string $pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string $mode Mode to leave.
$this->_regexes[$mode]->addPattern($pattern, "__exit");
* Adds a pattern that has a special mode. Acts as an entry
* and exit pattern in one go, effectively calling a special
* parser handler for this token only.
* @param string $pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string $mode Should only apply this
* pattern when dealing with
* @param string $special Use this mode for this one token.
$this->_regexes[$mode]->addPattern($pattern, "_$special");
* Adds a mapping from a mode to another handler.
* @param string $mode Mode to be remapped.
* @param string $handler New target handler.
* Splits the page text into tokens. Will fail
* if the handlers report an error or if no
* content is consumed. If successful then each
* unparsed and parsed token invokes a call to the
* @param string $raw Raw HTML text.
* @return boolean True on success, else false.
while (is_array($parsed =
$this->_reduce($raw))) {
list
($raw, $unmatched, $matched, $mode) =
$parsed;
if (! $this->_dispatchTokens($unmatched, $matched, $mode)) {
if (strlen($raw) ==
$length) {
return $this->_invokeParser($raw, LEXER_UNMATCHED);
* Sends the matched token and any leading unmatched
* text to the parser changing the lexer to a new
* @param string $unmatched Unmatched leading portion.
* @param string $matched Actual token match.
* @param string $mode Mode after match. A boolean
* false mode causes no change.
* @return boolean False if there was any error
function _dispatchTokens($unmatched, $matched, $mode =
false) {
if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) {
return $this->_invokeParser($matched, LEXER_MATCHED);
if ($this->_isModeEnd($mode)) {
if (! $this->_invokeParser($matched, LEXER_EXIT)) {
return $this->_mode->leave();
if ($this->_isSpecialMode($mode)) {
$this->_mode->enter($this->_decodeSpecial($mode));
if (! $this->_invokeParser($matched, LEXER_SPECIAL)) {
return $this->_mode->leave();
$this->_mode->enter($mode);
return $this->_invokeParser($matched, LEXER_ENTER);
* Tests to see if the new mode is actually to leave
* the current mode and pop an item from the matching
* @param string $mode Mode to test.
* @return boolean True if this is the exit mode.
function _isModeEnd($mode) {
return ($mode ===
"__exit");
* Test to see if the mode is one where this mode
* is entered for this token only and automatically
* leaves immediately afterwoods.
* @param string $mode Mode to test.
* @return boolean True if this is the exit mode.
function _isSpecialMode($mode) {
return (strncmp($mode, "_", 1) ==
0);
* Strips the magic underscore marking single token
* @param string $mode Mode to decode.
* @return string Underlying mode name.
function _decodeSpecial($mode) {
* Calls the parser method named after the current
* mode. Empty content will be ignored. The lexer
* has a parser handler for each mode in the lexer.
* @param string $content Text parsed.
* @param boolean $is_match Token is recognised rather
function _invokeParser($content, $is_match) {
if (($content ===
'') ||
($content ===
false)) {
return $this->_parser->$handler($content, $is_match);
* Tries to match a chunk of text and if successful
* removes the recognised chunk and any leading
* unparsed data. Empty strings will not be matched.
* @param string $raw The subject to parse. This is the
* content that will be eaten.
* @return array/boolean Three item list of unparsed
* content followed by the
* recognised token and finally the
* action the parser is to take.
* True if no match, false if there
if ($action =
$this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) {
$unparsed_character_count =
strpos($raw, $match);
$unparsed =
substr($raw, 0, $unparsed_character_count);
$raw =
substr($raw, $unparsed_character_count +
strlen($match));
return array($raw, $unparsed, $match, $action);
* Breaks HTML into SAX events.
* Sets up the lexer with case insensitive matching
* and adds the HTML handlers.
* @param SimpleSaxParser $parser Handling strategy by
foreach ($this->_getParsedTags() as $tag) {
$this->_addInTagTokens();
* List of parsed tags. Others are ignored.
* @return array List of searched for tags.
function _getParsedTags() {
return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select',
'option', 'frameset', 'frame', 'label');
* The lexer has to skip certain sections such
* as server code, client code and styles.
function _addSkipping() {
* Pattern matches to start and end a tag.
* @param string $tag Name of tag to scan for.
* Pattern matches to parse the inside of a tag
* including the attributes and their quoting.
function _addInTagTokens() {
$this->_addAttributeTokens();
* Matches attributes that are either single quoted,
* double quoted or unquoted.
function _addAttributeTokens() {
$this->mapHandler('dq_attribute', 'acceptAttributeToken');
$this->mapHandler('sq_attribute', 'acceptAttributeToken');
$this->mapHandler('uq_attribute', 'acceptAttributeToken');
* Converts HTML tokens into selected SAX events.
* @param SimpleSaxListener $listener SAX event handler.
* Runs the content through the lexer which
* should call back to the acceptors.
* @param string $raw Page text to parse.
* @return boolean False if parse error.
return $this->_lexer->parse($raw);
* Sets up the matching lexer. Starts in 'text' mode.
* @param SimpleSaxParser $parser Event generator, usually $self.
* @return SimpleLexer Lexer suitable for this parser.
* Accepts a token from the tag mode. If the
* starting element completes then the element
* is dispatched and the current attributes
* set back to empty. The element or attribute
* name is converted to lower case.
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
if ($event ==
LEXER_ENTER) {
if ($event ==
LEXER_EXIT) {
* Accepts a token from the end tag mode.
* The element name is converted to lower case.
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
if (! preg_match('/<\/(.*)>/', $token, $matches)) {
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
if ($event ==
LEXER_UNMATCHED) {
if ($event ==
LEXER_SPECIAL) {
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
* Character data between tags regarded as
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
* Incoming data to be ignored.
* @param string $token Incoming characters.
* @param integer $event Lexer event type.
* @return boolean False if parse error.
function ignore($token, $event) {
* Decodes any HTML entities.
* @param string $html Incoming HTML.
* @return string Outgoing plain text.
* Turns HTML into text browser visible text. Images
* are converted to their alt text and tags are supressed.
* Entities are converted to their visible representation.
* @param string $html HTML to convert.
* @return string Plain text.
$text =
preg_replace('|<script[^>]*>.*?</script>|', '', $text);
$text =
preg_replace('|<img[^>]*alt\s*=\s*"([^"]*)"[^>]*>|', ' \1 ', $text);
$text =
preg_replace('|<img[^>]*alt\s*=\s*\'([^\']*)\'[^>]*>|', ' \1 ', $text);
$text =
preg_replace('|<img[^>]*alt\s*=\s*([a-zA-Z_]+)[^>]*>|', ' \1 ', $text);
return trim(trim($text), "\xA0"); // TODO: The \xAO is a . Add a test for this.
* Sets the document to write to.
* Start of element event.
* @param string $name Element name.
* @param hash $attributes Name value pairs.
* Attributes without content
* @return boolean False on parse error.
* @param string $name Element name.
* @return boolean False on parse error.
* Unparsed, but relevant data.
* @param string $text May include unparsed tags.
* @return boolean False on parse error.
Documentation generated on Sun, 04 May 2008 09:21:55 -0500 by phpDocumentor 1.3.0