From 6845c00a3f752abecd9ef763848329bceaf63df4 Mon Sep 17 00:00:00 2001 From: xue <> Date: Fri, 31 Mar 2006 12:42:22 +0000 Subject: Reorganized folders under framework. This may break existing applications. --- framework/Util/TDataFieldAccessor.php | 117 ++++++ framework/Util/TLogRouter.php | 666 ++++++++++++++++++++++++++++++++ framework/Util/TLogger.php | 130 +++++++ framework/Util/TSimpleDateFormatter.php | 354 +++++++++++++++++ framework/Util/TVarDumper.php | 123 ++++++ 5 files changed, 1390 insertions(+) create mode 100644 framework/Util/TDataFieldAccessor.php create mode 100644 framework/Util/TLogRouter.php create mode 100644 framework/Util/TLogger.php create mode 100644 framework/Util/TSimpleDateFormatter.php create mode 100644 framework/Util/TVarDumper.php (limited to 'framework/Util') diff --git a/framework/Util/TDataFieldAccessor.php b/framework/Util/TDataFieldAccessor.php new file mode 100644 index 00000000..09512a28 --- /dev/null +++ b/framework/Util/TDataFieldAccessor.php @@ -0,0 +1,117 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Util + */ + +/** + * TDataFieldAccessor class + * + * TDataFieldAccessor is a utility class that provides access to a field of some data. + * The accessor attempts to obtain the field value in the following order: + * - If the data is an array, then the field is treated as an array index + * and the corresponding element value is returned; + * - If the data is a TMap or TList object, then the field is treated as a key + * into the map or list, and the corresponding value is returned. + * - If the data is an object, the field is treated as a property or subproperty + * defined with getter methods. For example, if the object has a method called + * getMyValue(), then field 'MyValue' will retrive the result of this method call. + * If getMyValue() returns an object which contains a method getMySubValue(), + * then field 'MyValue.MySubValue' will return that method call result. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TDataFieldAccessor +{ + /** + * Evaluates the data value at the specified field. + * - If the data is an array, then the field is treated as an array index + * and the corresponding element value is returned; + * - If the data is a TMap or TList object, then the field is treated as a key + * into the map or list, and the corresponding value is returned. + * - If the data is an object, the field is treated as a property or subproperty + * defined with getter methods. For example, if the object has a method called + * getMyValue(), then field 'MyValue' will retrive the result of this method call. + * If getMyValue() returns an object which contains a method getMySubValue(), + * then field 'MyValue.MySubValue' will return that method call result. + * @param mixed data containing the field value, can be an array, TMap, TList or object. + * @param mixed field value + * @return mixed value at the specified field + * @throw TInvalidDataValueException if field or data is invalid + */ + public static function getDataFieldValue($data,$field) + { + if(Prado::getApplication()->getMode()===TApplication::STATE_PERFORMANCE) + { + if(is_array($data) || ($data instanceof ArrayAccess)) + return $data[$field]; + else if(is_object($data)) + { + if(strpos($field,'.')===false) // simple field + { + if(property_exists($data,$field)) + return $data->{$field}; + else + return call_user_func(array($data,'get'.$field)); + } + else // field in the format of xxx.yyy.zzz + { + $object=$data; + foreach(explode('.',$field) as $f) + $object=call_user_func(array($object,'get'.$f)); + return $object; + } + } + else + throw new TInvalidDataValueException('datafieldaccessor_data_invalid',$field); + } + else + { + if(is_array($data) || ($data instanceof ArrayAccess)) + { + if(isset($data[$field]) || $data[$field]===null) + return $data[$field]; + else + throw new TInvalidDataValueException('datafieldaccessor_datafield_invalid',$field); + } + else if(is_object($data)) + { + if(strpos($field,'.')===false) // simple field + { + if(property_exists($data,$field)) + return $data->{$field}; + else if(is_callable(array($data,'get'.$field))) + return call_user_func(array($data,'get'.$field)); + else + throw new TInvalidDataValueException('datafieldaccessor_datafield_invalid',$field); + } + else // field in the format of xxx.yyy.zzz + { + $object=$data; + foreach(explode('.',$field) as $f) + { + $getter='get'.$f; + if(is_callable(array($object,$getter))) + $object=call_user_func(array($object,$getter)); + else + throw new TInvalidDataValueException('datafieldaccessor_datafield_invalid',$field); + } + return $object; + } + } + else + throw new TInvalidDataValueException('datafieldaccessor_data_invalid',$field); + } + } +} + +?> \ No newline at end of file diff --git a/framework/Util/TLogRouter.php b/framework/Util/TLogRouter.php new file mode 100644 index 00000000..bdad8649 --- /dev/null +++ b/framework/Util/TLogRouter.php @@ -0,0 +1,666 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Util + */ + +/** + * TLogRouter class. + * + * TLogRouter manages routes that record log messages in different media different ways. + * For example, a file log route {@link TFileLogRoute} records log messages + * in log files. An email log route {@link TEmailLogRoute} sends log messages + * to email addresses. + * + * Log routes may be configured in application or page folder configuration files + * or an external configuration file specified by {@link setConfigFile ConfigFile}. + * The format is as follows, + * + * <route class="TFileLogRoute" Categories="System.Web.UI" Levels="Warning" /> + * <route class="TEmailLogRoute" Categories="Application" Levels="Fatal" Emails="admin@pradosoft.com" /> + * + * You can specify multiple routes with different filtering conditions and different + * targets, even if the routes are of the same type. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TLogRouter extends TModule +{ + /** + * File extension of external configuration file + */ + const CONFIG_FILE_EXT='.xml'; + /** + * @var array list of routes available + */ + private $_routes=array(); + /** + * @var string external configuration file + */ + private $_configFile=null; + + /** + * Initializes this module. + * This method is required by the IModule interface. + * @param TXmlElement configuration for this module, can be null + * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid. + */ + public function init($config) + { + if($this->_configFile!==null) + { + if(is_file($this->_configFile)) + { + $dom=new TXmlDocument; + $dom->loadFromFile($this->_configFile); + $this->loadConfig($dom); + } + else + throw new TConfigurationException('logrouter_configfile_invalid',$this->_configFile); + } + $this->loadConfig($config); + $this->getApplication()->attachEventHandler('OnEndRequest',array($this,'collectLogs')); + } + + /** + * Loads configuration from an XML element + * @param TXmlElement configuration node + * @throws TConfigurationException if log route class or type is not specified + */ + private function loadConfig($xml) + { + foreach($xml->getElementsByTagName('route') as $routeConfig) + { + $properties=$routeConfig->getAttributes(); + if(($class=$properties->remove('class'))===null) + throw new TConfigurationException('logrouter_routeclass_required'); + $route=Prado::createComponent($class); + if(!($route instanceof TLogRoute)) + throw new TConfigurationException('logrouter_routetype_invalid'); + foreach($properties as $name=>$value) + $route->setSubproperty($name,$value); + $this->_routes[]=$route; + $route->init($routeConfig); + } + } + + /** + * @return string external configuration file. Defaults to null. + */ + public function getConfigFile() + { + return $this->_configFile; + } + + /** + * @param string external configuration file in namespace format. The file + * must be suffixed with '.xml'. + * @throws TInvalidDataValueException if the file is invalid. + */ + public function setConfigFile($value) + { + if(($this->_configFile=Prado::getPathOfNamespace($value,self::LOG_FILE_EXT))===null) + throw new TConfigurationException('logrouter_configfile_invalid',$value); + } + + /** + * Collects log messages from a logger. + * This method is an event handler to application's EndRequest event. + * @param mixed event parameter + */ + public function collectLogs($param) + { + $logger=Prado::getLogger(); + foreach($this->_routes as $route) + $route->collectLogs($logger); + } +} + +/** + * TLogRoute class. + * + * TLogRoute is the base class for all log route classes. + * A log route object retrieves log messages from a logger and sends it + * somewhere, such as files, emails. + * The messages being retrieved may be filtered first before being sent + * to the destination. The filters include log level filter and log category filter. + * + * To specify level filter, set {@link setLevels Levels} property, + * which takes a string of comma-separated desired level names (e.g. 'Error, Debug'). + * To specify category filter, set {@link setCategories Categories} property, + * which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO'). + * + * Level filter and category filter are combinational, i.e., only messages + * satisfying both filter conditions will they be returned. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +abstract class TLogRoute extends TApplicationComponent +{ + /** + * @var array lookup table for level names + */ + protected static $_levelNames=array( + TLogger::DEBUG=>'Debug', + TLogger::INFO=>'Info', + TLogger::NOTICE=>'Notice', + TLogger::WARNING=>'Warning', + TLogger::ERROR=>'Error', + TLogger::ALERT=>'Alert', + TLogger::FATAL=>'Fatal' + ); + /** + * @var array lookup table for level values + */ + protected static $_levelValues=array( + 'debug'=>TLogger::DEBUG, + 'info'=>TLogger::INFO, + 'notice'=>TLogger::NOTICE, + 'warning'=>TLogger::WARNING, + 'error'=>TLogger::ERROR, + 'alert'=>TLogger::ALERT, + 'fatal'=>TLogger::FATAL + ); + /** + * @var integer log level filter (bits) + */ + private $_levels=null; + /** + * @var array log category filter + */ + private $_categories=null; + + /** + * Initializes the route. + * @param TXmlElement configurations specified in {@link TLogRouter}. + */ + public function init($config) + { + } + + /** + * @return integer log level filter + */ + public function getLevels() + { + return $this->_levels; + } + + /** + * @param integer|string integer log level filter (in bits). If the value is + * a string, it is assumed to be comma-separated level names. Valid level names + * include 'Debug', 'Info', 'Notice', 'Warning', 'Error', 'Alert' and 'Fatal'. + */ + public function setLevels($levels) + { + if(is_integer($levels)) + $this->_levels=$levels; + else + { + $this->_levels=null; + $levels=strtolower($levels); + foreach(explode(',',$levels) as $level) + { + $level=trim($level); + if(isset(self::$_levelValues[$level])) + $this->_levels|=self::$_levelValues[$level]; + } + } + } + + /** + * @return array list of categories to be looked for + */ + public function getCategories() + { + return $this->_categories; + } + + /** + * @param array|string list of categories to be looked for. If the value is a string, + * it is assumed to be comma-separated category names. + */ + public function setCategories($categories) + { + if(is_array($categories)) + $this->_categories=$categories; + else + { + $this->_categories=null; + foreach(explode(',',$categories) as $category) + { + if(($category=trim($category))!=='') + $this->_categories[]=$category; + } + } + } + + /** + * @param integer level value + * @return string level name + */ + protected function getLevelName($level) + { + return isset(self::$_levelNames[$level])?self::$_levelNames[$level]:'Unknown'; + } + + /** + * @param string level name + * @return integer level value + */ + protected function getLevelValue($level) + { + return isset(self::$_levelValues[$level])?self::$_levelValues[$level]:0; + } + + /** + * Formats a log message given different fields. + * @param string message content + * @param integer message level + * @param string message category + * @param integer timestamp + * @return string formatted message + */ + protected function formatLogMessage($message,$level,$category,$time) + { + return @date('M d H:i:s',$time).' ['.$this->getLevelName($level).'] ['.$category.'] '.$message."\n"; + } + + /** + * Retrieves log messages from logger to log route specific destination. + * @param TLogger logger instance + */ + public function collectLogs(TLogger $logger) + { + $logs=$logger->getLogs($this->getLevels(),$this->getCategories()); + if(!empty($logs)) + $this->processLogs($logs); + } + + /** + * Processes log messages and sends them to specific destination. + * Derived child classes must implement this method. + * @param array list of messages. Each array element is a (formatted) message string. + */ + abstract protected function processLogs($logs); +} + +/** + * TFileLogRoute class. + * + * TFileLogRoute records log messages in files. + * The log files are stored under {@link setLogPath LogPath} and the file name + * is specified by {@link setLogFile LogFile}. If the size of the log file is + * greater than {@link setMaxFileSize MaxFileSize} (in kilo-bytes), a rotation + * is performed, which renames the current log file by suffixing the file name + * with '.1'. All existing log files are moved backwards one place, i.e., '.2' + * to '.3', '.1' to '.2'. The property {@link setMaxLogFiles MaxLogFiles} + * specifies how many files to be kept. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TFileLogRoute extends TLogRoute +{ + /** + * @var integer maximum log file size + */ + private $_maxFileSize=512; // in KB + /** + * @var integer number of log files used for rotation + */ + private $_maxLogFiles=2; + /** + * @var string directory storing log files + */ + private $_logPath=null; + /** + * @var string log file name + */ + private $_logFile='prado.log'; + + /** + * @return string directory storing log files. Defaults to application runtime path. + */ + public function getLogPath() + { + if($this->_logPath===null) + $this->_logPath=$this->getApplication()->getRuntimePath(); + return $this->_logPath; + } + + /** + * @param string directory (in namespace format) storing log files. + * @throws TConfigurationException if log path is invalid + */ + public function setLogPath($value) + { + if(($this->_logPath=Prado::getPathOfNamespace($value))===null || !is_dir($this->_logPath) || !is_writable($this->_logPath)) + throw new TConfigurationException('filelogroute_logpath_invalid',$value); + } + + /** + * @return string log file name. Defaults to 'prado.log'. + */ + public function getLogFile() + { + return $this->_logFile; + } + + /** + * @param string log file name + */ + public function setLogFile($value) + { + $this->_logFile=$value; + } + + /** + * @return integer maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB). + */ + public function getMaxFileSize() + { + return $this->_maxFileSize; + } + + /** + * @param integer maximum log file size in kilo-bytes (KB). + * @throws TInvalidDataValueException if the value is smaller than 1. + */ + public function setMaxFileSize($value) + { + $this->_maxFileSize=TPropertyValue::ensureInteger($value); + if($this->_maxFileSize<=0) + throw new TInvalidDataValueException('filelogroute_maxfilesize_invalid'); + } + + /** + * @return integer number of files used for rotation. Defaults to 2. + */ + public function getMaxLogFiles() + { + return $this->_maxLogFiles; + } + + /** + * @param integer number of files used for rotation. + */ + public function setMaxLogFiles($value) + { + $this->_maxLogFiles=TPropertyValue::ensureInteger($value); + if($this->_maxLogFiles<1) + throw new TInvalidDataValueException('filelogroute_maxlogfiles_invalid'); + } + + /** + * Saves log messages in files. + * @param array list of log messages + */ + protected function processLogs($logs) + { + $logFile=$this->getLogPath().'/'.$this->getLogFile(); + if(@filesize($logFile)>$this->_maxFileSize*1024) + $this->rotateFiles(); + foreach($logs as $log) + error_log($this->formatLogMessage($log[0],$log[1],$log[2],$log[3]),3,$logFile); + } + + /** + * Rotates log files. + */ + protected function rotateFiles() + { + $file=$this->getLogPath().'/'.$this->getLogFile(); + for($i=$this->_maxLogFiles;$i>0;--$i) + { + $rotateFile=$file.'.'.$i; + if(is_file($rotateFile)) + { + if($i===$this->_maxLogFiles) + unlink($rotateFile); + else + rename($rotateFile,$file.'.'.($i+1)); + } + } + if(is_file($file)) + rename($file,$file.'.1'); + } +} + +/** + * TEmailLogRoute class. + * + * TEmailLogRoute sends selected log messages to email addresses. + * The target email addresses may be specified via {@link setEmails Emails} property. + * Optionally, you may set the email {@link setSubject Subject} and the + * {@link setSentFrom SentFrom} address. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TEmailLogRoute extends TLogRoute +{ + /** + * Regex pattern for email address. + */ + const EMAIL_PATTERN='/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/'; + /** + * Default email subject. + */ + const DEFAULT_SUBJECT='Prado Application Log'; + /** + * @var array list of destination email addresses. + */ + private $_emails=array(); + /** + * @var string email subject + */ + private $_subject=''; + /** + * @var string email sent from address + */ + private $_from=''; + + /** + * Initializes the route. + * @param TXmlElement configurations specified in {@link TLogRouter}. + * @throws TConfigurationException if {@link getSentFrom SentFrom} is empty and + * 'sendmail_from' in php.ini is also empty. + */ + public function init($config) + { + if($this->_from==='') + $this->_from=ini_get('sendmail_from'); + if($this->_from==='') + throw new TConfigurationException('emaillogroute_sentfrom_required'); + } + + /** + * Sends log messages to specified email addresses. + * @param array list of log messages + */ + protected function processLogs($logs) + { + $message=''; + foreach($logs as $log) + $message.=$this->formatLogMessage($log[0],$log[1],$log[2],$log[3]); + $message=wordwrap($message,70); + foreach($this->_emails as $email) + mail($email,$this->getSubject(),$message,"From:{$this->_from}\r\n"); + + } + + /** + * @return array list of destination email addresses + */ + public function getEmails() + { + return $this->_emails; + } + + /** + * @return array|string list of destination email addresses. If the value is + * a string, it is assumed to be comma-separated email addresses. + */ + public function setEmails($emails) + { + if(is_array($emails)) + $this->_emails=$emails; + else + { + $this->_emails=array(); + foreach(explode(',',$emails) as $email) + { + $email=trim($email); + if(preg_match(self::EMAIL_PATTERN,$email)) + $this->_emails[]=$email; + } + } + } + + /** + * @return string email subject. Defaults to TEmailLogRoute::DEFAULT_SUBJECT + */ + public function getSubject() + { + if($this->_subject===null) + $this->_subject=self::DEFAULT_SUBJECT; + return $this->_subject; + } + + /** + * @param string email subject. + */ + public function setSubject($value) + { + $this->_subject=$value; + } + + /** + * @return string send from address of the email + */ + public function getSentFrom() + { + return $this->_from; + } + + /** + * @param string send from address of the email + */ + public function setSentFrom($value) + { + $this->_from=$value; + } +} + +/** + * TBrowserLogRoute class. + * + * TBrowserLogRoute prints selected log messages in the response. + * + * @author Xiang Wei Zhuo + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TBrowserLogRoute extends TLogRoute +{ + public function processLogs($logs) + { + if(empty($logs) || $this->getApplication()->getMode()==='Performance') return; + $first = $logs[0][3]; + $prev = $first; + $even = true; + $response = $this->getApplication()->getResponse(); + $response->write($this->renderHeader()); + foreach($logs as $log) + { + $timing['total'] = $log[3] - $first; + $timing['delta'] = $log[3] - $prev; + $timing['even'] = !($even = !$even); + $prev=$log[3]; + $response->write($this->renderMessage($log,$timing)); + } + $response->write($this->renderFooter()); + } + + protected function renderHeader() + { + $string = << + + + Application Log + + +   + CategoryMessageTime Spent (s)Cumulated Time Spent (s) + +EOD; + return $string; + } + + protected function renderMessage($log, $info) + { + $bgcolor = $info['even'] ? "#fff" : "#eee"; + $total = sprintf('%0.6f', $info['total']); + $delta = sprintf('%0.6f', $info['delta']); + $color = $this->getColorLevel($log[1]); + $msg = preg_replace('/\(line[^\)]+\)$/','',$log[0]); //remove line number info + $msg = THttpUtility::htmlEncode($msg); + $string = << +   + {$log[2]} + {$msg} + {$delta} + {$total} + +EOD; + return $string; + } + + protected function getColorLevel($level) + { + switch($level) + { + case TLogger::DEBUG: return 'green'; + case TLogger::INFO: return 'black'; + case TLogger::NOTICE: return '#3333FF'; + case TLogger::WARNING: return '#33FFFF'; + case TLogger::ERROR: return '#ff9933'; + case TLogger::ALERT: return '#ff00ff'; + case TLogger::FATAL: return 'red'; + } + return ''; + } + + protected function renderFooter() + { + $string = ""; + foreach(self::$_levelValues as $name => $level) + { + $string .= "getColorLevel($level); + $string .= ";margin: 0.5em;\">".strtoupper($name).""; + } + $string .= ""; + return $string; + } +} +?> \ No newline at end of file diff --git a/framework/Util/TLogger.php b/framework/Util/TLogger.php new file mode 100644 index 00000000..632c46f1 --- /dev/null +++ b/framework/Util/TLogger.php @@ -0,0 +1,130 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Util + */ + +/** + * TLogger class. + * + * TLogger records log messages in memory and implements the methods to + * retrieve the messages with filter conditions, including log levels and + * log categories. + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TLogger extends TComponent +{ + /** + * Log levels. + */ + const DEBUG=0x01; + const INFO=0x02; + const NOTICE=0x04; + const WARNING=0x08; + const ERROR=0x10; + const ALERT=0x20; + const FATAL=0x40; + /** + * @var array log messages + */ + private $_logs=array(); + /** + * @var integer log levels (bits) to be filtered + */ + private $_levels; + /** + * @var array list of categories to be filtered + */ + private $_categories; + + /** + * Logs a message. + * Messages logged by this method may be retrieved via {@link getLogs}. + * @param string message to be logged + * @param integer level of the message. Valid values include + * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING, + * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL. + * @param string category of the message + */ + public function log($message,$level,$category='Uncategorized') + { + $this->_logs[]=array($message,$level,$category,microtime(true)); + } + + /** + * Retrieves log messages. + * Messages may be filtered by log levels and/or categories. + * A level filter is specified by an integer, whose bits indicate the levels interested. + * For example, (TLogger::INFO | TLogger::WARNING) specifies INFO and WARNING levels. + * A category filter is specified by concatenating interested category names + * with commas. A message whose category name starts with any filtering category + * will be returned. For example, a category filter 'System.Web, System.IO' + * will return messages under categories such as 'System.Web', 'System.IO', + * 'System.Web.UI', 'System.Web.UI.WebControls', etc. + * Level filter and category filter are combinational, i.e., only messages + * satisfying both filter conditions will they be returned. + * @param integer level filter + * @param string category filter + * @param array list of messages. Each array elements represents one message + * with the following structure: + * array( + * [0] => message + * [1] => level + * [2] => category + * [3] => timestamp); + */ + public function getLogs($levels=null,$categories=null) + { + $this->_levels=$levels; + $this->_categories=$categories; + if(empty($levels) && empty($categories)) + return $this->_logs; + else if(empty($levels)) + return array_values(array_filter(array_filter($this->_logs,array($this,'filterByCategories')))); + else if(empty($categories)) + return array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevels')))); + else + { + $ret=array_values(array_filter(array_filter($this->_logs,array($this,'filterByLevels')))); + return array_values(array_filter(array_filter($ret,array($this,'filterByCategories')))); + } + } + + /** + * Filter function used by {@link getLogs} + * @param array element to be filtered + */ + private function filterByCategories($value) + { + foreach($this->_categories as $category) + { + if($value[2]===$category || strpos($value[2],$category.'.')===0) + return $value; + } + return false; + } + + /** + * Filter function used by {@link getLogs} + * @param array element to be filtered + */ + private function filterByLevels($value) + { + if($value[1] & $this->_levels) + return $value; + else + return false; + } +} + +?> \ No newline at end of file diff --git a/framework/Util/TSimpleDateFormatter.php b/framework/Util/TSimpleDateFormatter.php new file mode 100644 index 00000000..ce92a272 --- /dev/null +++ b/framework/Util/TSimpleDateFormatter.php @@ -0,0 +1,354 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2006 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Util + */ + +/** + * TSimpleDateFormatter class. + * + * Formats and parses dates using the SimpleDateFormat pattern. + * This pattern is compatible with the I18N and java's SimpleDateFormatter. + * + * Pattern | Description + * ---------------------------------------------------- + * d | Day of month 1 to 31, no padding + * dd | Day of monath 01 to 31, zero leading + * M | Month digit 1 to 12, no padding + * MM | Month digit 01 to 12, zero leading + * yy | 2 year digit, e.g., 96, 05 + * yyyy | 4 year digit, e.g., 2005 + * ---------------------------------------------------- + * + * + * Usage example, to format a date + * + * $formatter = new TSimpleDateFormatter("dd/MM/yyy"); + * echo $formatter->format(time()); + * + * + * To parse the date string into a date timestamp. + * + * $formatter = new TSimpleDateFormatter("d-M-yyy"); + * echo $formatter->parse("24-6-2005"); + * + * + * @author Wei Zhuo + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TSimpleDateFormatter +{ + /** + * Formatting pattern. + * @var string + */ + private $pattern; + + /** + * Charset, default is 'UTF-8' + * @var string + */ + private $charset = 'UTF-8'; + + /** + * Constructor, create a new date time formatter. + * @param string formatting pattern. + * @param string pattern and value charset + */ + public function __construct($pattern, $charset='UTF-8') + { + $this->setPattern($pattern); + $this->setCharset($charset); + } + + /** + * @return string formatting pattern. + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * @param string formatting pattern. + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + } + + /** + * @return string formatting charset. + */ + public function getCharset() + { + return $this->charset; + } + + /** + * @param string formatting charset. + */ + public function setCharset($charset) + { + $this->charset = $charset; + } + + /** + * Format the date according to the pattern. + * @param string|int the date to format, either integer or a string readable by strtotime. + * @return string formatted date. + */ + public function format($value) + { + $date = $this->getDate($value); + $bits['yyyy'] = $date['year']; + $bits['yy'] = substr("{$date['year']}", -2); + + $bits['MM'] = str_pad("{$date['mon']}", 2, '0', STR_PAD_LEFT); + $bits['M'] = $date['mon']; + + $bits['dd'] = str_pad("{$date['mday']}", 2, '0', STR_PAD_LEFT); + $bits['d'] = $date['mday']; + + return str_replace(array_keys($bits), $bits, $this->pattern); + } + + public function getMonthPattern() + { + if(is_int(strpos($this->pattern, 'MMMM'))) + return 'MMMM'; + if(is_int(strpos($this->pattern, 'MMM'))) + return 'MMM'; + if(is_int(strpos($this->pattern, 'MM'))) + return 'MM'; + if(is_int(strpos($this->pattern, 'M'))) + return 'M'; + return false; + } + + public function getDayPattern() + { + if(is_int(strpos($this->pattern, 'dd'))) + return 'dd'; + if(is_int(strpos($this->pattern, 'd'))) + return 'd'; + return false; + } + + public function getYearPattern() + { + if(is_int(strpos($this->pattern, 'yyyy'))) + return 'yyyy'; + if(is_int(strpos($this->pattern, 'yy'))) + return 'yy'; + return false; + } + + public function getDayMonthYearOrdering() + { + $ordering = array(); + if(is_int($day= strpos($this->pattern, 'd'))) + $ordering['day'] = $day; + if(is_int($month= strpos($this->pattern, 'M'))) + $ordering['month'] = $month; + if(is_int($year= strpos($this->pattern, 'yy'))) + $ordering['year'] = $year; + asort($ordering); + return array_keys($ordering); + } + + /** + * Gets the time stamp from string or integer. + * @param string|int date to parse + * @return int parsed date time stamp + */ + private function getDate($value) + { + if(is_int($value)) + return @getdate($value); + $date = @strtotime($value); + if($date < 0) + throw new TInvalidDataValueException('invalid_date', $value); + return @getdate($date); + } + + /** + * @return boolean true if the given value matches with the date pattern. + */ + public function isValidDate($value) + { + return !is_null($this->parse($value, false)); + } + + /** + * Parse the string according to the pattern. + * @param string date string to parse + * @return int date time stamp + * @throws TInvalidDataValueException if date string is malformed. + */ + public function parse($value,$defaultToCurrentTime=true) + { + if(!is_string($value)) + throw new TInvalidDataValueException('date_to_parse_must_be_string', $value); + + if(empty($this->pattern)) return time(); + + $date = $this->getDate(time()); + + if($this->length(trim($value)) < 1) + return $defaultToCurrentTime ? $date : null; + + $pattern = $this->pattern; + + $i_val = 0; + $i_format = 0; + $pattern_length = $this->length($pattern); + $c = ''; + $token=''; + $x=null; $y=null; + + + if($defaultToCurrentTime) + { + $year = "{$date['year']}"; + $month = $date['mon']; + $day = $date['mday']; + } + else + { + $year = null; + $month = null; + $day = null; + } + + while ($i_format < $pattern_length) + { + $c = $this->charAt($pattern,$i_format); + $token=''; + while ($this->charEqual($pattern, $i_format, $c) + && ($i_format < $pattern_length)) + { + $token .= $this->charAt($pattern, $i_format++); + } + + if ($token=='yyyy' || $token=='yy' || $token=='y') + { + if ($token=='yyyy') { $x=4;$y=4; } + if ($token=='yy') { $x=2;$y=2; } + if ($token=='y') { $x=2;$y=4; } + $year = $this->getInteger($value,$i_val,$x,$y); + if(is_null($year)) + throw new TInvalidDataValueException('Invalid year', $value); + $i_val += strlen($year); + if(strlen($year) == 2) + { + $iYear = intval($year); + if($iYear > 70) + $year = $iYear + 1900; + else + $year = $iYear + 2000; + } + $year = intval($year); + } + elseif($token=='MM' || $token=='M') + { + $month=$this->getInteger($value,$i_val, + $this->length($token),2); + $iMonth = intval($month); + if(is_null($month) || $iMonth < 1 || $iMonth > 12 ) + throw new TInvalidDataValueException('Invalid month', $value); + $i_val += strlen($month); + $month = $iMonth; + } + elseif ($token=='dd' || $token=='d') + { + $day = $this->getInteger($value,$i_val, + $this->length($token), 2); + $iDay = intval($day); + if(is_null($day) || $iDay < 1 || $iDay >31) + throw new TInvalidDataValueException('Invalid day', $value); + $i_val += strlen($day); + $day = $iDay; + } + else + { + if($this->substring($value, $i_val, $this->length($token)) != $token) + throw new TInvalidDataValueException("Subpattern '{$this->pattern}' mismatch", $value); + else + $i_val += $this->length($token); + } + } + if ($i_val != $this->length($value)) + throw new TInvalidDataValueException("Pattern '{$this->pattern}' mismatch", $value); + + if(!$defaultToCurrentTime && (is_null($month) || is_null($day) || is_null($year))) + return null; + else + return $this->getDate(@mktime(0, 0, 0, $month, $day, $year)); + } + + /** + * Calculate the length of a string, may be consider iconv_strlen? + */ + private function length($string) + { + //use iconv_strlen or just strlen? + return strlen($string); + } + + /** + * Get the char at a position. + */ + private function charAt($string, $pos) + { + return $this->substring($string, $pos, 1); + } + + /** + * Gets a portion of a string, uses iconv_substr. + */ + private function substring($string, $start, $length) + { + return iconv_substr($string, $start, $length); + } + + /** + * Returns true if char at position equals a particular char. + */ + private function charEqual($string, $pos, $char) + { + return $this->charAt($string, $pos) == $char; + } + + /** + * Gets integer from part of a string, allows integers of any length. + * @param string string to retrieve the integer from. + * @param int starting position + * @param int minimum integer length + * @param int maximum integer length + * @return string integer portition of the string, null otherwise + */ + private function getInteger($str,$i,$minlength,$maxlength) + { + //match for digits backwards + for ($x = $maxlength; $x >= $minlength; $x--) + { + $token= $this->substring($str, $i,$x); + if ($this->length($token) < $minlength) + return null; + if (preg_match('/^\d+$/', $token)) + return $token; + } + return null; + } +} + +?> \ No newline at end of file diff --git a/framework/Util/TVarDumper.php b/framework/Util/TVarDumper.php new file mode 100644 index 00000000..0532a6ec --- /dev/null +++ b/framework/Util/TVarDumper.php @@ -0,0 +1,123 @@ + + * @link http://www.pradosoft.com/ + * @copyright Copyright © 2005 PradoSoft + * @license http://www.pradosoft.com/license/ + * @version $Revision: $ $Date: $ + * @package System.Util + */ + +/** + * TVarDumper class. + * + * TVarDumper is intended to replace the buggy PHP function var_dump and print_r. + * It can correctly identify the recursively referenced objects in a complex + * object structure. It also has a recurisve depth control to avoid indefinite + * recursive display of some peculiar variables. + * + * TVarDumper can be used as follows, + * + * echo TVarDumper::dump($var); + * + * + * @author Qiang Xue + * @version $Revision: $ $Date: $ + * @package System.Util + * @since 3.0 + */ +class TVarDumper +{ + private static $_objects; + private static $_output; + private static $_depth; + + /** + * Converts a variable into a string representation. + * This method achieves the similar functionality as var_dump and print_r + * but is more robust when handling complex objects such as PRADO controls. + * @param mixed variable to be dumped + * @param integer maximum depth that the dumper should go into the variable. Defaults to 10. + * @return string the string representation of the variable + */ + public static function dump($var,$depth=10) + { + self::$_output=''; + self::$_objects=array(); + self::$_depth=$depth; + self::dumpInternal($var,0); + return self::$_output; + } + + private static function dumpInternal($var,$level) + { + switch(gettype($var)) + { + case 'boolean': + self::$_output.=$var?'true':'false'; + break; + case 'integer': + self::$_output.="$var"; + break; + case 'double': + self::$_output.="$var"; + break; + case 'string': + self::$_output.="'$var'"; + break; + case 'resource': + self::$_output.='{resource}'; + break; + case 'NULL': + self::$_output.="null"; + break; + case 'unknown type': + self::$_output.='{unknown}'; + break; + case 'array': + if(self::$_depth<=$level) + self::$_output.='array(...)'; + else if(empty($var)) + self::$_output.='array()'; + else + { + $keys=array_keys($var); + $spaces=str_repeat(' ',$level*4); + self::$_output.="array\n".$spaces.'('; + foreach($keys as $key) + { + self::$_output.="\n".$spaces." [$key] => "; + self::$_output.=self::dumpInternal($var[$key],$level+1); + } + self::$_output.="\n".$spaces.')'; + } + break; + case 'object': + if(($id=array_search($var,self::$_objects,true))!==false) + self::$_output.=get_class($var).'#'.($id+1).'(...)'; + else if(self::$_depth<=$level) + self::$_output.=get_class($var).'(...)'; + else + { + $id=array_push(self::$_objects,$var); + $className=get_class($var); + $members=(array)$var; + $keys=array_keys($members); + $spaces=str_repeat(' ',$level*4); + self::$_output.="$className#$id\n".$spaces.'('; + foreach($keys as $key) + { + $keyDisplay=strtr(trim($key),array("\0"=>':')); + self::$_output.="\n".$spaces." [$keyDisplay] => "; + self::$_output.=self::dumpInternal($members[$key],$level+1); + } + self::$_output.="\n".$spaces.')'; + } + break; + } + } +} + +?> \ No newline at end of file -- cgit v1.2.3