cvs: pear /Net_GameServerQuery Match.php

From: Date: Tue, 29 Jun 2004 18:58:11 +0000
Subject: cvs: pear /Net_GameServerQuery Match.php
Groups: php.pear.cvs 
Request: Send a blank email to pear-cvs+get-21272@lists.php.net to get a copy of this message
ortega Tue Jun 29 14:58:11 2004 EDT Added files: /pear/Net_GameServerQuery Match.php Log: String Parser example.

http://cvs.php.net/co.php/pear/Net_GameServerQuery/Match.php?r=1.1&p=1 Index: pear/Net_GameServerQuery/Match.php +++ pear/Net_GameServerQuery/Match.php <?php // +----------------------------------------------------------------------+ // | PHP Version 5 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2004 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://au.php.net/license/3_0.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Tom Buskens <ortega@php.net> | // +----------------------------------------------------------------------+ // // $id$ // $revision$ /* Error messages */ define('NET_GAMESERVERQUERY_PARSESTRING_UNEXPPATTERN', 'unexpected pattern'); define('NET_GAMESERVERQUERY_PARSESTRING_RULENOTSET', 'rule not set'); define('NET_GAMESERVERQUERY_PARSESTRING_INVDATATYPE', 'invalid data type'); define('NET_GAMESERVERQUERY_PARSESTRING_INVTYPELENGTH', 'invalid type length'); define('NET_GAMESERVERQUERY_PARSESTRING_NOTEMP', 'temp value not found'); /** * Net_GameServerQuery_ParseString * * @version 0.0 * @package Net_GameServerQuery */ class Net_GameServerQuery_ParseString { /** * Server response * * @var string * @access private */ private $_string; /** * Last matched string * * @var string * @access private */ private $_currentMatch; /** * Rules to apply to current string * * @var array * @acess private */ private $_currentRules; /** * Formatted data * * @var mixed array * @access private */ private $_output; /** * Temporary data * * @var mixed array * @access private */ private $_temp; /** * Prints out error, should be changed * * @access private * @param string $errmsg The error message * @param int $errno The error number */ private function _throwError($errmsg, $errno) { $message = '<p>Fatal error ('.$errno.'): '.$errmsg."</p>\n"; print_r($this->_output); die($message); } /** * Matches and processes input according to pattern array * * @access public * @param string $string The server response * @param array $rules The array containing processing information * @return array The parsed string data */ public function parse($string, $rules) { /* Initialize variables */ $this->_string = $string; $this->_output = array(); $this->_temp = array(); /* Parse string */ $this->_parseString($rules); /* Return formatted data */ return $this->_output; } /** * Recursively walks through array, processing the server response * * @access private * @param array $rules The array containing processing information * @param int $currentDepth Current depth of the array */ private function _parseString($rules, $currentDepth = 0) { /* Parse string while pattern matches */ $x = count($rules); $loopcount = 0; while (true) { for ($i = 0; $i != $x; $i++) { /* Rule is an array, recursively apply array */ if (is_array($rules[$i])) { $this->_parseString($rules[$i], $currentDepth + 1); } /* Normal rule, apply it */ elseif (isset($rules[$i])) { if (!$this->_applyRule($rules[$i])) { /* Don't throw error when the loop is at the beginning, * except when on base level with 0 loops executed (i.e * empty string */ if ($i === 0 && !($currentDepth === 0 && $loopcount === 0)) { return true; } /* Throw error */ else { /* Could not apply rule, throw error */ $this->_throwError(NET_GAMESERVERQUERY_PARSESTRING_UNEXPPATTERN, 0); } } } /* Rule not set */ else { $this->_throwError(NET_GAMESERVERQUERY_PARSESTRING_RULENOTSET, 1); } } ++$loopcount; } } /** * Applies rule to string * * @access private * @param string $rule String containing processing information */ private function _applyRule($rule) { /* Get parsing info from rule */ $this->_getRule($rule); /* Match string */ if (!$this->_matchString()) { return false; } else { /* Convert match to proper type */ $this->_matchToType(); /* Store value in output array */ $this->_storeMatch(); /* Store value in temp array */ $this->_storeMatchTemp(); return true; } } /** * Retrieves data from rule string * * @access private * @param string $rule String containing processing information */ private function _getRule($ruleString) { /* Split string, get pieces */ $pieces = explode('|', $ruleString); switch(count($pieces)) { case 4: $rule['temp'] = $pieces[3]; case 3: $rule['type'] = $pieces[1]; $rule['name'] = $pieces[2]; case 1: $rule['pattern'] = $pieces[0]; break; /* Invalid format, throw error */ default: $this->_throwError(NET_GAMESERVERQUERY_PARSESTRING_INVDATATYPE, 2); break; } $this->_currentRules = $rule; } /** * Matches server response with regular expression * * @access private * @return Bool True if string was matched, false otherwise */ private function _matchString() { /* Format pattern */ $pattern = '/^'.$this->_currentRules['pattern'].'/'; /* Match pattern, remove match from string */ if (preg_match($pattern, $this->_string, $match)) { $this->_currentMatch = $match[0]; $this->_string = substr($this->_string, strlen($this->_currentMatch)); return true; } /* No match */ else { return false; } } /** * Converts last match according to data type * * @access private */ private function _matchToType() { /* Convert current match according to type */ if (isset($this->_currentRules['type'])) { $type = $this->_currentRules['type']; /* Check length */ $length = array ( 'int32' => 4, 'float32' => 4, 'int16' => 2, 'byte' => 1 ); if (isset($length[$type]) && strlen($this->_currentMatch) !== $length[$type]) { /* TODO: throw error */ $this->_throwError(NET_GAMESERVERQUERY_PARSESTRING_INVTYPELENGTH, 3); } /* Format according to type */ switch ($type) { case 'int16': $unpack = unpack('Sshort', $this->_currentMatch); $this->_currentMatch = $unpack['short']; break; case 'int32': /* TODO */ break; case 'float32': /* TODO */ break; case 'byte': $this->_currentMatch = ord($this->_currentMatch); break; case 'string': break; default: /* TODO: Throw error */ } } } /** * Stores current match in output array * * @access private */ private function _storeMatch() { /* Get variable name */ if (!empty($this->_currentRules['name'])) { $name = $this->_currentRules['name']; if ($name{0} === '$') { $name = substr($name, 1); if (isset($this->_temp[$name])) { $name = $this->_temp[$name]; } /* Error */ else { $this->_throwError(NET_GAMESERVERQUERY_PARSESTRING_NOTEMP, 4); } } /* Old variable */ if (isset($this->_output[$name])) { /* Variable has 1 value, put it into an array */ if (!is_array($this->_output[$name])) { $this->_output[$name] = array($this->_output[$name]); } /* Add current match to array */ array_push($this->_output[$name], $this->_currentMatch); } /* Fresh variable */ else { $this->_output[$name] = $this->_currentMatch; } } } /** * Stores current match in temporary array * * @access private */ private function _storeMatchTemp() { /* store current match in temp array, overwrite any existing data */ if (isset($this->_currentRules['temp'])) { $varname = substr($this->_currentRules['temp'], 1); $this->_temp[$varname] = $this->_currentMatch; } } } /* Halflife rules example */ $rules = array( '\xff\xff\xff\xff', '.{2}|int16|rulecount', '\\x00', array( '[^\\x00]+|string||$varname', '\\x00', '[^\\x00]+|string|$varname', '\\x00' ) ); /* String: */ $string = 'ÿÿÿÿE]_tutor_bomb_viewable_check_interval0.5_tutor_debug_level0_tutor_examine_time0.5_tutor_hint_interval_time10.0_tutor_look_angle10_tutor_look_distance200_tutor_message_character_display_time_coefficient0.07_tutor_message_minimum_display_time1_tutor_message_repeats5_tutor_view_distance1000admin_highlander0admin_ignore_immunity0admin_mod_version2.50.59 (MM)admin_quiet0allow_client_exec1allow_spectators1.0ami_sv_maxplayers16amv_private_server0coop0deathmatch1decalfrequency30default_access0edgefriction2hostage_debug0humans_join_teamanymax_queries_sec1max_queries_sec_global1max_queries_window1metamod_version1.17mp_allowmonsters0mp_autokick0mp_autoteambalance1mp_buytime1.5mp_c4timer35mp_chattime10mp_consistency1mp_fadetoblack0mp_flashlight0mp_footsteps1mp_forcecamera0mp_forcechasecam0mp_fragsleft0mp_freezetime7mp_friendlyfire0mp_ghostfrequency0.4mp_hostagepenalty3mp_kickpercent0.66mp_limitteams1mp_logdetail0mp_logfile1mp_logmessages1mp_mapvoteratio0.66mp_maxrounds0mp_mirrordamage0mp_playerid0mp_roundtime3mp_startmoney800mp_timeleft0mp_timelimit30mp_tkpunish0mp_windifference1mp_winlimit0pausable0public_slots_free16reserve_slots0reserve_type0sv_accelerate5sv_aim0sv_airaccelerate3sv_airmove1sv_allowupload1sv_alltalk0sv_bounce1'; /* Call function */ $p = new Net_GameServerQuery_ParseString; print_r($p->parse($string, $rules)); ?>
« previous php.pear.cvs (#21272) next »