You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by ih...@apache.org on 2012/08/18 19:27:27 UTC

svn commit: r1374617 - in /logging/log4php/trunk/src: main/php/ main/php/configurators/ main/php/helpers/ test/php/appenders/ test/php/helpers/

Author: ihabunek
Date: Sat Aug 18 17:27:26 2012
New Revision: 1374617

URL: http://svn.apache.org/viewvc?rev=1374617&view=rev
Log:
Reimplemented variable (actually constants) substitution in parameters. 
Removed deprecated variable substitution and option conversion methods.

Modified:
    logging/log4php/trunk/src/main/php/LoggerConfigurable.php
    logging/log4php/trunk/src/main/php/LoggerReflectionUtils.php
    logging/log4php/trunk/src/main/php/configurators/LoggerConfiguratorDefault.php
    logging/log4php/trunk/src/main/php/helpers/LoggerOptionConverter.php
    logging/log4php/trunk/src/test/php/appenders/LoggerAppenderPDOTest.php
    logging/log4php/trunk/src/test/php/helpers/LoggerOptionConverterTest.php

Modified: logging/log4php/trunk/src/main/php/LoggerConfigurable.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/main/php/LoggerConfigurable.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/main/php/LoggerConfigurable.php (original)
+++ logging/log4php/trunk/src/main/php/LoggerConfigurable.php Sat Aug 18 17:27:26 2012
@@ -99,7 +99,8 @@ abstract class LoggerConfigurable {
 			}
 		} else {
 			try {
-				$this->$property = LoggerOptionConverter::toStringEx($value);
+				$value = LoggerOptionConverter::toStringEx($value);
+				$this->$property = LoggerOptionConverter::substConstants($value);
 			} catch (Exception $ex) {
 				$value = var_export($value, true);
 				$this->warn("Invalid value given for '$property' property: [$value]. Expected a string. Property not changed.");

Modified: logging/log4php/trunk/src/main/php/LoggerReflectionUtils.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/main/php/LoggerReflectionUtils.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/main/php/LoggerReflectionUtils.php (original)
+++ logging/log4php/trunk/src/main/php/LoggerReflectionUtils.php Sat Aug 18 17:27:26 2012
@@ -65,7 +65,6 @@ class LoggerReflectionUtils {
 	 * @param array $properties An array containing keys and values.
 	 * @param string $prefix Only keys having the specified prefix will be set.
 	 */
-	 // TODO: check, if this is really useful
 	public function setProperties($properties, $prefix) {
 		$len = strlen($prefix);
 		reset($properties);
@@ -74,7 +73,7 @@ class LoggerReflectionUtils {
 				if(strpos($key, '.', ($len + 1)) > 0) {
 					continue;
 				}
-				$value = LoggerOptionConverter::findAndSubst($key, $properties);
+				$value = $properties[$key];
 				$key = substr($key, $len);
 				if($key == 'layout' and ($this->obj instanceof LoggerAppender)) {
 					continue;

Modified: logging/log4php/trunk/src/main/php/configurators/LoggerConfiguratorDefault.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/main/php/configurators/LoggerConfiguratorDefault.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/main/php/configurators/LoggerConfiguratorDefault.php (original)
+++ logging/log4php/trunk/src/main/php/configurators/LoggerConfiguratorDefault.php Sat Aug 18 17:27:26 2012
@@ -451,10 +451,10 @@ class LoggerConfiguratorDefault implemen
 		
 		// Set logger additivity
 		if (isset($config['additivity'])) {
-			$additivity = LoggerOptionConverter::toBoolean($config['additivity'], null);
-			if (is_bool($additivity)) {
+			try {
+				$additivity = LoggerOptionConverter::toBooleanEx($config['additivity'], null);
 				$logger->setAdditivity($additivity);
-			} else {
+			} catch (Exception $ex) {
 				$this->warn("Invalid additivity value [{$config['additivity']}] specified for logger [$loggerName]. Ignoring additivity setting.");
 			}
 		}

Modified: logging/log4php/trunk/src/main/php/helpers/LoggerOptionConverter.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/main/php/helpers/LoggerOptionConverter.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/main/php/helpers/LoggerOptionConverter.php (original)
+++ logging/log4php/trunk/src/main/php/helpers/LoggerOptionConverter.php Sat Aug 18 17:27:26 2012
@@ -27,11 +27,6 @@
  * @since 0.5
  */
 class LoggerOptionConverter {
-
-	const DELIM_START = '${';
-	const DELIM_STOP = '}';
-	const DELIM_START_LEN = 2;
-	const DELIM_STOP_LEN = 1;
 	
 	/** String values which are converted to boolean TRUE. */
 	private static $trueValues = array('1', 'true', 'yes', 'on');
@@ -70,37 +65,6 @@ class LoggerOptionConverter {
 		}
 	}
 
-	/**
-	 * If <var>$value</var> is <i>true</i>, then <i>true</i> is
-	 * returned. If <var>$value</var> is <i>false</i>, then
-	 * <i>true</i> is returned. Otherwise, <var>$default</var> is
-	 * returned.
-	 *
-	 * <p>Case of value is unimportant.</p>
-	 *
-	 * @param string $value
-	 * @param boolean $default
-	 * @return boolean
-	 */
-	public static function toBoolean($value, $default=true) {
-		if (is_null($value)) {
-			return $default;
-		} elseif (is_string($value)) {
-			$trimmedVal = strtolower(trim($value));
-			if("1" == $trimmedVal or "true" == $trimmedVal or "yes" == $trimmedVal or "on" == $trimmedVal) {
-				return true;
-			} else if ("" == $trimmedVal or "0" == $trimmedVal or "false" == $trimmedVal or "no" == $trimmedVal or "off" == $trimmedVal) {
-				return false;
-			}
-		} elseif (is_bool($value)) {
-			return $value;
-		} elseif (is_int($value)) {
-			return !($value == 0); // true is everything but 0 like in C 
-		}
-		
-		return $default;
-	}
-
 	/** Converts $value to boolean, or throws an exception if not possible. */
 	public static function toBooleanEx($value) {
 		if (isset($value)) {
@@ -119,21 +83,6 @@ class LoggerOptionConverter {
 		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to boolean.");
 	}
 	
-	/**
-	 * @param string $value
-	 * @param integer $default
-	 * @return integer
-	 */
-	public static function toInt($value, $default) {
-		$value = trim($value);
-		if(is_numeric($value)) {
-			return (int)$value;
-		} else {
-			return $default;
-		}
-	}
-	
-	
 	/** 
 	 * Converts $value to integer, or throws an exception if not possible. 
 	 * Floats cannot be converted to integer.
@@ -164,68 +113,6 @@ class LoggerOptionConverter {
 		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a positive integer.");
 	}
 
-	/**
-	 * Converts a standard or custom priority level to a Level
-	 * object.
-	 *
-	 * <p> If <var>$value</var> is of form "<b>level#full_file_classname</b>",
-	 * where <i>full_file_classname</i> means the class filename with path
-	 * but without php extension, then the specified class' <i>toLevel()</i> method
-	 * is called to process the specified level string; if no '#'
-	 * character is present, then the default {@link LoggerLevel}
-	 * class is used to process the level value.</p>
-	 *
-	 * <p>As a special case, if the <var>$value</var> parameter is
-	 * equal to the string "NULL", then the value <i>null</i> will
-	 * be returned.</p>
-	 *
-	 * <p>If any error occurs while converting the value to a level,
-	 * the <var>$defaultValue</var> parameter, which may be
-	 * <i>null</i>, is returned.</p>
-	 *
-	 * <p>Case of <var>$value</var> is insignificant for the level level, but is
-	 * significant for the class name part, if present.</p>
-	 *
-	 * @param string $value
-	 * @param LoggerLevel $defaultValue
-	 * @return LoggerLevel a {@link LoggerLevel} or null
-	 */
-	public static function toLevel($value, $defaultValue) {
-		if($value === null) {
-			return $defaultValue;
-		}
-		$hashIndex = strpos($value, '#');
-		if($hashIndex === false) {
-			if("NULL" == strtoupper($value)) {
-				return null;
-			} else {
-				// no class name specified : use standard Level class
-				return LoggerLevel::toLevel($value, $defaultValue);
-			}
-		}
-
-		$result = $defaultValue;
-
-		$clazz = substr($value, ($hashIndex + 1));
-		$levelName = substr($value, 0, $hashIndex);
-
-		// This is degenerate case but you never know.
-		if("NULL" == strtoupper($levelName)) {
-			return null;
-		}
-
-		$clazz = basename($clazz);
-
-		if(class_exists($clazz)) {
-			$result = @call_user_func(array($clazz, 'toLevel'), $levelName, $defaultValue);
-			if(!$result instanceof LoggerLevel) {
-				$result = $defaultValue;
-			}
-		} 
-		return $result;
-	}
-	
-	
 	/** Converts the value to a level. Throws an exception if not possible. */
 	public static function toLevelEx($value) {
 		if ($value instanceof LoggerLevel) {
@@ -239,35 +126,6 @@ class LoggerOptionConverter {
 	}
 
 	/**
-	 * @param string $value
-	 * @param float $default
-	 * @return float
-	 */
-	public static function toFileSize($value, $default) {
-		if($value === null) {
-			return $default;
-		}
-
-		$string = strtoupper(trim($value));
-		$multiplier = (float)1;
-		if(($index = strpos($string, 'KB')) !== false) {
-			$multiplier = 1024;
-			$string = substr($string, 0, $index);
-		} else if(($index = strpos($string, 'MB')) !== false) {
-			$multiplier = 1024 * 1024;
-			$string = substr($string, 0, $index);
-		} else if(($index = strpos($string, 'GB')) !== false) {
-			$multiplier = 1024 * 1024 * 1024;
-			$string = substr($string, 0, $index);
-		}
-		if(is_numeric($string)) {
-			return (float)$string * $multiplier;
-		} 
-		return $default;
-	}
-	
-
-	/**
 	 * Converts a value to a valid file size (integer).
 	 * 
 	 * Supports 'KB', 'MB' and 'GB' suffixes, where KB = 1024 B etc. 
@@ -337,115 +195,32 @@ class LoggerOptionConverter {
 		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to string.");
 	}
 	
-	
 	/**
-	 * Find the value corresponding to <var>$key</var> in
-	 * <var>$props</var>. Then perform variable substitution on the
-	 * found value.
-	 *
-	 * @param string $key
-	 * @param array $props
-	 * @return string
-	 */
-	public static function findAndSubst($key, $props) {
-		$value = @$props[$key];
-
-		// If coming from the LoggerConfiguratorIni, some options were
-		// already mangled by parse_ini_file:
-		//
-		// not specified      => never reaches this code
-		// ""|off|false|null  => string(0) ""
-		// "1"|on|true        => string(1) "1"
-		// "true"             => string(4) "true"
-		// "false"            => string(5) "false"
-		// 
-		// As the integer 1 and the boolean true are therefore indistinguable
-		// it's up to the setter how to deal with it, they can not be cast
-		// into a boolean here. {@see toBoolean}
-		// Even an empty value has to be given to the setter as it has been
-		// explicitly set by the user and is different from an option which
-		// has not been specified and therefore keeps its default value.
-		//
-		// if(!empty($value)) {
-			return LoggerOptionConverter::substVars($value, $props);
-		// }
-	}
-
-	/**
-	 * Perform variable substitution in string <var>$val</var> from the
-	 * values of keys found with the {@link getSystemProperty()} method.
-	 * 
-	 * <p>The variable substitution delimeters are <b>${</b> and <b>}</b>.
+	 * Performs value substitution for string options.
 	 * 
-	 * <p>For example, if the "MY_CONSTANT" contains "value", then
-	 * the call
-	 * <code>
-	 * $s = LoggerOptionConverter::substVars("Value of key is ${MY_CONSTANT}.");
-	 * </code>
-	 * will set the variable <i>$s</i> to "Value of key is value.".</p>
+	 * An option can contain PHP constants delimited by '${' and '}'.
 	 * 
-	 * <p>If no value could be found for the specified key, then the
-	 * <var>$props</var> parameter is searched, if the value could not
-	 * be found there, then substitution defaults to the empty string.</p>
+	 * E.g. for input string "some ${FOO} value", the method will attempt 
+	 * to substitute ${FOO} with the value of constant FOO if it exists.
 	 * 
-	 * <p>For example, if {@link getSystemProperty()} cannot find any value for the key
-	 * "inexistentKey", then the call
-	 * <code>
-	 * $s = LoggerOptionConverter::substVars("Value of inexistentKey is [${inexistentKey}]");
-	 * </code>
-	 * will set <var>$s</var> to "Value of inexistentKey is []".</p>
+	 * Therefore, if FOO is a constant, and it has value "bar", the resulting 
+	 * string will be "some bar value". 
 	 * 
-	 * <p>A warn is thrown if <var>$val</var> contains a start delimeter "${" 
-	 * which is not balanced by a stop delimeter "}" and an empty string is returned.</p>
+	 * If the constant is not defined, it will be replaced by an empty string, 
+	 * and the resulting string will be "some  value". 
 	 * 
-	 * @param string $val The string on which variable substitution is performed.
-	 * @param array $props
+	 * @param string $string String on which to perform substitution.
 	 * @return string
 	 */
-	 // TODO: this method doesn't work correctly with key = true, it needs key = "true" which is odd
-	public static function substVars($val, $props = null) {
-		$sbuf = '';
-		$i = 0;
-		while(true) {
-			$j = strpos($val, self::DELIM_START, $i);
-			if($j === false) {
-				// no more variables
-				if($i == 0) { // this is a simple string
-					return $val;
-				} else { // add the tail string which contails no variables and return the result.
-					$sbuf .= substr($val, $i);
-					return $sbuf;
-				}
-			} else {
-			
-				$sbuf .= substr($val, $i, $j-$i);
-				$k = strpos($val, self::DELIM_STOP, $j);
-				if($k === false) {
-					// LoggerOptionConverter::substVars() has no closing brace. Opening brace
-					return '';
-				} else {
-					$j += self::DELIM_START_LEN;
-					$key = substr($val, $j, $k - $j);
-					// first try in System properties
-					$replacement = LoggerOptionConverter::getSystemProperty($key, null);
-					// then try props parameter
-					if($replacement == null and $props !== null) {
-						$replacement = @$props[$key];
-					}
-
-					if(!empty($replacement)) {
-						// Do variable substitution on the replacement string
-						// such that we can solve "Hello ${x2}" as "Hello p1" 
-						// the where the properties are
-						// x1=p1
-						// x2=${x1}
-						$recursiveReplacement = LoggerOptionConverter::substVars($replacement, $props);
-						$sbuf .= $recursiveReplacement;
-					}
-					$i = $k + self::DELIM_STOP_LEN;
-				}
-			}
+	public static function substConstants($string) {
+		preg_match_all('/\${([^}]+)}/', $string, $matches);
+		
+		foreach($matches[1] as $key => $match) {
+			$match = trim($match);
+			$search = $matches[0][$key];
+			$replacement = defined($match) ? constant($match) : '';
+			$string = str_replace($search, $replacement, $string);
 		}
+		return $string;
 	}
-
 }

Modified: logging/log4php/trunk/src/test/php/appenders/LoggerAppenderPDOTest.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/test/php/appenders/LoggerAppenderPDOTest.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/test/php/appenders/LoggerAppenderPDOTest.php (original)
+++ logging/log4php/trunk/src/test/php/appenders/LoggerAppenderPDOTest.php Sat Aug 18 17:27:26 2012
@@ -37,8 +37,6 @@ class LoggerAppenderPDOTest extends PHPU
 		self::$file = PHPUNIT_TEMP_DIR . '/' . self::FILENAME;
 		self::$dsn = 'sqlite:' . self::$file;
 		
-// 		var_dump(self::$file, self::$dsn); die;
-		
 		if(extension_loaded('pdo_sqlite')) {
 			$drop = 'DROP TABLE IF EXISTS log4php_log;';
 			$create = 'CREATE TABLE log4php_log (

Modified: logging/log4php/trunk/src/test/php/helpers/LoggerOptionConverterTest.php
URL: http://svn.apache.org/viewvc/logging/log4php/trunk/src/test/php/helpers/LoggerOptionConverterTest.php?rev=1374617&r1=1374616&r2=1374617&view=diff
==============================================================================
--- logging/log4php/trunk/src/test/php/helpers/LoggerOptionConverterTest.php (original)
+++ logging/log4php/trunk/src/test/php/helpers/LoggerOptionConverterTest.php Sat Aug 18 17:27:26 2012
@@ -32,26 +32,6 @@ define('MY_CONSTANT_CONSTANT_OTHER', 'DE
 class LoggerOptionConverterTest extends PHPUnit_Framework_TestCase {
 
     public function testToBoolean() {
-        self::assertTrue(LoggerOptionConverter::toBoolean(null, true));
-        self::assertTrue(LoggerOptionConverter::toBoolean('foo', true));
-        self::assertTrue(LoggerOptionConverter::toBoolean(null));
-        self::assertTrue(LoggerOptionConverter::toBoolean(true));
-        self::assertTrue(LoggerOptionConverter::toBoolean("1"));
-        self::assertTrue(LoggerOptionConverter::toBoolean(1));
-        self::assertTrue(LoggerOptionConverter::toBoolean("true"));
-        self::assertTrue(LoggerOptionConverter::toBoolean("on"));
-        self::assertTrue(LoggerOptionConverter::toBoolean("yes"));
-        
-        self::assertFalse(LoggerOptionConverter::toBoolean(null, false));
-        self::assertFalse(LoggerOptionConverter::toBoolean('foo', false));
-        self::assertFalse(LoggerOptionConverter::toBoolean(false));
-        self::assertFalse(LoggerOptionConverter::toBoolean(""));
-        self::assertFalse(LoggerOptionConverter::toBoolean("0"));
-        self::assertFalse(LoggerOptionConverter::toBoolean(0));
-        self::assertFalse(LoggerOptionConverter::toBoolean("false"));
-        self::assertFalse(LoggerOptionConverter::toBoolean("off"));
-        self::assertFalse(LoggerOptionConverter::toBoolean("no"));
-        
         self::assertTrue(LoggerOptionConverter::toBooleanEx(1));
         self::assertTrue(LoggerOptionConverter::toBooleanEx("1"));
         self::assertTrue(LoggerOptionConverter::toBooleanEx(true));
@@ -86,12 +66,6 @@ class LoggerOptionConverterTest extends 
     }
     
     public function testToInteger() {
-    	self::assertSame(1, LoggerOptionConverter::toInt('1', 0));
-    	self::assertSame(-11, LoggerOptionConverter::toInt('-11', 0));
-    	self::assertSame(-10, LoggerOptionConverter::toInt(null, -10));
-    	self::assertSame(-10, LoggerOptionConverter::toInt('', -10));
-    	self::assertSame(-10, LoggerOptionConverter::toInt('foo', -10));
-    	
     	self::assertSame(1, LoggerOptionConverter::toIntegerEx('1'));
     	self::assertSame(1, LoggerOptionConverter::toIntegerEx(1));
     	self::assertSame(0, LoggerOptionConverter::toIntegerEx('0'));
@@ -145,21 +119,29 @@ class LoggerOptionConverterTest extends 
     	LoggerOptionConverter::toIntegerEx(false);
     }
     
-    public function testSubstituteVars() {
-    	$props['OTHER_CONSTANT'] = "OTHER";
-    	$props['MY_CONSTANT'] = "TEST";
-    	$props['NEXT_CONSTANT'] = "NEXT";
-        
-        $result = LoggerOptionConverter::substVars('Value of key is ${MY_CONSTANT}.', $props);
+    public function testSubstituteConstants() {
+    	define('OTHER_CONSTANT', 'OTHER');
+    	define('MY_CONSTANT', 'TEST');
+    	define('NEXT_CONSTANT', 'NEXT');
+     
+        $result = LoggerOptionConverter::substConstants('Value of key is ${MY_CONSTANT}.');
         self::assertEquals('Value of key is TEST.', $result);
         
-        $result = LoggerOptionConverter::substVars('Value of key is ${MY_CONSTANT} or ${OTHER_CONSTANT}.', $props);
+        $result = LoggerOptionConverter::substConstants('Value of key is ${MY_CONSTANT} or ${OTHER_CONSTANT}.');
         self::assertEquals('Value of key is TEST or OTHER.', $result);
         
-        $result = LoggerOptionConverter::substVars('Value of key is ${MY_CONSTANT_CONSTANT}.', $props);
+        $result = LoggerOptionConverter::substConstants('Value of key is ${MY_CONSTANT_CONSTANT}.');
         self::assertEquals('Value of key is DEFINE.', $result);
         
-        $result = LoggerOptionConverter::substVars('Value of key is ${MY_CONSTANT_CONSTANT} or ${MY_CONSTANT_CONSTANT_OTHER}.', $props);
+        $result = LoggerOptionConverter::substConstants('Value of key is ${MY_CONSTANT_CONSTANT} or ${MY_CONSTANT_CONSTANT_OTHER}.');
         self::assertEquals('Value of key is DEFINE or DEFINE_OTHER.', $result);
     }
+    
+    public function testActualSubstituteConstants() {
+    	$a = new LoggerAppenderFile();
+    	$a->setFile('${PHPUNIT_TEMP_DIR}/log.txt');
+    	$actual = $a->getFile();
+    	$expected = PHPUNIT_TEMP_DIR . '/log.txt';
+    	self::assertSame($expected, $actual);
+    }
 }
\ No newline at end of file