OSDN Git Service

初回コミット(v2.6.17.1)
[magic3/magic3.git] / include / lib / log4php / helpers / LoggerOptionConverter.php
1 <?php
2 /**
3  * log4php is a PHP port of the log4j java logging package.
4  * 
5  * <p>This framework is based on log4j (see {@link http://jakarta.apache.org/log4j log4j} for details).</p>
6  * <p>Design, strategies and part of the methods documentation are developed by log4j team 
7  * (Ceki Gülcü as log4j project founder and 
8  * {@link http://jakarta.apache.org/log4j/docs/contributors.html contributors}).</p>
9  *
10  * <p>PHP port, extensions and modifications by VxR. All rights reserved.<br>
11  * For more information, please see {@link http://www.vxr.it/log4php/}.</p>
12  *
13  * <p>This software is published under the terms of the LGPL License
14  * a copy of which has been included with this distribution in the LICENSE file.</p>
15  * 
16  * @package log4php
17  * @subpackage helpers
18  */
19
20 /**
21  * @ignore 
22  */
23 if (!defined('LOG4PHP_DIR')) define('LOG4PHP_DIR', dirname(__FILE__) . '/..');
24
25 require_once(LOG4PHP_DIR . '/LoggerLevel.php');
26
27 define('LOG4PHP_OPTION_CONVERTER_DELIM_START',      '${');
28 define('LOG4PHP_OPTION_CONVERTER_DELIM_STOP',       '}');
29 define('LOG4PHP_OPTION_CONVERTER_DELIM_START_LEN',  2);
30 define('LOG4PHP_OPTION_CONVERTER_DELIM_STOP_LEN',   1);
31
32 /**
33  * A convenience class to convert property values to specific types.
34  *
35  * @author VxR <vxr@vxr.it>
36  * @version $Revision: 2 $ 
37  * @package log4php
38  * @subpackage helpers
39  * @static
40  * @since 0.5
41  */
42 class LoggerOptionConverter {
43
44     /** 
45      * OptionConverter is a static class. 
46      */
47     function OptionConverter() 
48     {
49         return;
50     }
51
52     /**
53      * @param array $l
54      * @param array $r
55      * @return array
56      *
57      * @static
58      */
59     function concatanateArrays($l, $r)
60     {
61         return array_merge($l, $r);
62     }
63
64     /**
65     * Read a predefined var.
66     *
67     * It returns a value referenced by <var>$key</var> using this search criteria:
68     * - if <var>$key</var> is a constant then return it. Else
69     * - if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
70     * - return <var>$def</var>. 
71     *
72     * @param string $key The key to search for.
73     * @param string $def The default value to return.
74     * @return string    the string value of the system property, or the default
75     *                   value if there is no property with that key.
76     *
77     * @static
78     */
79     function getSystemProperty($key, $def)
80     {
81         LoggerLog::debug("LoggerOptionConverter::getSystemProperty():key=[{$key}]:def=[{$def}].");
82
83         if (defined($key)) {
84             return (string)constant($key);
85         } elseif (isset($_ENV[$key])) {
86             return (string)$_ENV[$key];
87         } else {
88             return $def;
89         }
90     }
91
92     /**
93      * If <var>$value</var> is <i>true</i>, then <i>true</i> is
94      * returned. If <var>$value</var> is <i>false</i>, then
95      * <i>true</i> is returned. Otherwise, <var>$default</var> is
96      * returned.
97      *
98      * <p>Case of value is unimportant.</p>
99      *
100      * @param string $value
101      * @param boolean $default
102      * @return boolean
103      *
104      * @static
105      */
106     function toBoolean($value, $default)
107     {
108         if($value === null)
109             return $default;
110         if ($value == 1)
111             return true;
112         $trimmedVal = strtolower(trim($value));
113         if ("true" == $trimmedVal or "yes" == $trimmedVal)
114             return true;
115         if ("false" == $trimmedVal)
116             return false;
117         return $default;
118     }
119
120     /**
121      * @param string $value
122      * @param integer $default
123      * @return integer
124      * @static
125      */
126     function toInt($value, $default)
127     {
128         $value = trim($value);
129         if (is_numeric($value)) {
130             return (int)$value;
131         } else {
132             return $default;
133         }
134     }
135
136     /**
137      * Converts a standard or custom priority level to a Level
138      * object.
139      *
140      * <p> If <var>$value</var> is of form "<b>level#full_file_classname</b>",
141      * where <i>full_file_classname</i> means the class filename with path
142      * but without php extension, then the specified class' <i>toLevel()</i> method
143      * is called to process the specified level string; if no '#'
144      * character is present, then the default {@link LoggerLevel}
145      * class is used to process the level value.</p>
146      *
147      * <p>As a special case, if the <var>$value</var> parameter is
148      * equal to the string "NULL", then the value <i>null</i> will
149      * be returned.</p>
150      *
151      * <p>If any error occurs while converting the value to a level,
152      * the <var>$defaultValue</var> parameter, which may be
153      * <i>null</i>, is returned.</p>
154      *
155      * <p>Case of <var>$value</var> is insignificant for the level level, but is
156      * significant for the class name part, if present.</p>
157      *
158      * @param string $value
159      * @param LoggerLevel $defaultValue
160      * @return LoggerLevel a {@link LoggerLevel} or null
161      * @static
162      */
163     //function toLevel($value, $defaultValue)           // \8fC\90³(2006/12/12)
164         static function toLevel($value, $defaultValue)
165     {
166         if($value === null)
167             return $defaultValue;
168
169         $hashIndex = strpos($value, '#');
170         if ($hashIndex === false) {
171             if("NULL" == strtoupper($value)) {
172                     return null;
173             } else {
174                     // no class name specified : use standard Level class
175                     return LoggerLevel::toLevel($value, $defaultValue);
176             }
177         }
178
179         $result = $defaultValue;
180
181         $clazz = substr($value, ($hashIndex + 1));
182         $levelName = substr($value, 0, $hashIndex);
183
184         // This is degenerate case but you never know.
185         if("NULL" == strtoupper($levelName)) {
186                 return null;
187         }
188
189         LoggerLog::debug("LoggerOptionConverter::toLevel():class=[{$clazz}]:pri=[{$levelName}]");
190
191         if (!class_exists($clazz))
192             @include_once("{$clazz}.php");
193
194         $clazz = basename($clazz);
195
196         if (class_exists($clazz)) {
197             $result = @call_user_func(array($clazz, 'toLevel'), $value, $defaultValue);
198             //if (!is_a($result, 'loggerlevel')) {
199                         if (!($result instanceof LoggerLevel)){         // \8fC\90³(2006/12/12)
200                 LoggerLog::debug("LoggerOptionConverter::toLevel():class=[{$clazz}] cannot call toLevel(). Returning default.");            
201                 $result = $defaultValue;
202             }
203         } else {
204             LoggerLog::warn("LoggerOptionConverter::toLevel() class '{$clazz}' doesnt exists.");
205         }
206         return $result;
207     }
208
209     /**
210      * @param string $value
211      * @param float $default
212      * @return float
213      *
214      * @static
215      */
216     function toFileSize($value, $default)
217     {
218         if ($value === null)
219             return $default;
220
221         $s = strtoupper(trim($value));
222         $multiplier = (float)1;
223         if(($index = strpos($s, 'KB')) !== false) {
224             $multiplier = 1024;
225             $s = substr($s, 0, $index);
226         } elseif(($index = strpos($s, 'MB')) !== false) {
227             $multiplier = 1024 * 1024;
228             $s = substr($s, 0, $index);
229         } elseif(($index = strpos($s, 'GB')) !== false) {
230             $multiplier = 1024 * 1024 * 1024;
231             $s = substr($s, 0, $index);
232         }
233         if(is_numeric($s)) {
234             return (float)$s * $multiplier;
235         } else {
236             LoggerLog::warn("LoggerOptionConverter::toFileSize() [{$s}] is not in proper form.");
237         }
238         return $default;
239     }
240
241     /**
242      * Find the value corresponding to <var>$key</var> in
243      * <var>$props</var>. Then perform variable substitution on the
244      * found value.
245      *
246      * @param string $key
247      * @param array $props
248      * @return string
249      *
250      * @static
251      */
252     //function findAndSubst($key, $props)
253         static function findAndSubst($key, $props)              // \8fC\90³(2006/12/12)
254     {
255         $value = @$props[$key];
256         if(empty($value)) {
257             return null;
258         }
259         return LoggerOptionConverter::substVars($value, $props);
260     }
261
262     /**
263      * Perform variable substitution in string <var>$val</var> from the
264      * values of keys found with the {@link getSystemProperty()} method.
265      * 
266      * <p>The variable substitution delimeters are <b>${</b> and <b>}</b>.
267      * 
268      * <p>For example, if the "MY_CONSTANT" contains "value", then
269      * the call
270      * <code>
271      * $s = LoggerOptionConverter::substituteVars("Value of key is ${MY_CONSTANT}.");
272      * </code>
273      * will set the variable <i>$s</i> to "Value of key is value.".</p>
274      * 
275      * <p>If no value could be found for the specified key, then the
276      * <var>$props</var> parameter is searched, if the value could not
277      * be found there, then substitution defaults to the empty string.</p>
278      * 
279      * <p>For example, if {@link getSystemProperty()} cannot find any value for the key
280      * "inexistentKey", then the call
281      * <code>
282      * $s = LoggerOptionConverter::substVars("Value of inexistentKey is [${inexistentKey}]");
283      * </code>
284      * will set <var>$s</var> to "Value of inexistentKey is []".</p>
285      * 
286      * <p>A warn is thrown if <var>$val</var> contains a start delimeter "${" 
287      * which is not balanced by a stop delimeter "}" and an empty string is returned.</p>
288      * 
289      * @log4j-author Avy Sharell
290      * 
291      * @param string $val The string on which variable substitution is performed.
292      * @param array $props
293      * @return string
294      *
295      * @static
296      */
297     //function substVars($val, $props = null)
298         static function substVars($val, $props = null)          // \8fC\90³(2006/12/12)
299     {
300         LoggerLog::debug("LoggerOptionConverter::substVars():val=[{$val}]");
301         
302         $sbuf = '';
303         $i = 0;
304         while(true) {
305             $j = strpos($val, LOG4PHP_OPTION_CONVERTER_DELIM_START, $i);
306             if ($j === false) {
307                 LoggerLog::debug("LoggerOptionConverter::substVars() no more variables");
308                     // no more variables
309                     if ($i == 0) { // this is a simple string
310                     LoggerLog::debug("LoggerOptionConverter::substVars() simple string");
311                         return $val;
312                 } else { // add the tail string which contails no variables and return the result.
313                     $sbuf .= substr($val, $i);
314                     LoggerLog::debug("LoggerOptionConverter::substVars():sbuf=[{$sbuf}]. Returning sbuf");                    
315                     return $sbuf;
316                     }
317             } else {
318             
319                     $sbuf .= substr($val, $i, $j-$i);
320                 LoggerLog::debug("LoggerOptionConverter::substVars():sbuf=[{$sbuf}]:i={$i}:j={$j}.");
321                 $k = strpos($val, LOG4PHP_OPTION_CONVERTER_DELIM_STOP, $j);
322                 if ($k === false) {
323                     LoggerLog::warn(
324                         "LoggerOptionConverter::substVars() " .
325                         "'{$val}' has no closing brace. Opening brace at position {$j}."
326                     );
327                     return '';
328                     } else {
329                         $j += LOG4PHP_OPTION_CONVERTER_DELIM_START_LEN;
330                         $key = substr($val, $j, $k - $j);
331                     // first try in System properties
332                         $replacement = LoggerOptionConverter::getSystemProperty($key, null);
333                         // then try props parameter
334                         if($replacement == null and $props !== null) {
335                         $replacement = @$props[$key];
336                         }
337
338                     if(!empty($replacement)) {
339                             // Do variable substitution on the replacement string
340                             // such that we can solve "Hello ${x2}" as "Hello p1" 
341                         // the where the properties are
342                             // x1=p1
343                         // x2=${x1}
344                             $recursiveReplacement = LoggerOptionConverter::substVars($replacement, $props);
345                             $sbuf .= $recursiveReplacement;
346                         }
347                         $i = $k + LOG4PHP_OPTION_CONVERTER_DELIM_STOP_LEN;
348                     }
349             }
350         }
351     }
352
353 }
354 ?>