source: branches/comu-ver2/data/module/log4php/php4/log4php/helpers/LoggerOptionConverter.php @ 18220

Revision 18220, 12.4 KB checked in by yokkuns, 15 years ago (diff)

#149 ロガークラス作成

Line 
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 */
23if (!defined('LOG4PHP_DIR')) define('LOG4PHP_DIR', dirname(__FILE__) . '/..');
24
25require_once(LOG4PHP_DIR . '/LoggerLevel.php');
26
27define('LOG4PHP_OPTION_CONVERTER_DELIM_START',      '${');
28define('LOG4PHP_OPTION_CONVERTER_DELIM_STOP',       '}');
29define('LOG4PHP_OPTION_CONVERTER_DELIM_START_LEN',  2);
30define('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: 1.5 $
37 * @package log4php
38 * @subpackage helpers
39 * @static
40 * @since 0.5
41 */
42class 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  public
66  static
67  String convertSpecialChars(String s) {
68    char c;
69    int len = s.length();
70    StringBuffer sbuf = new StringBuffer(len);
71
72    int i = 0;
73    while(i < len) {
74      c = s.charAt(i++);
75      if (c == '\\') {
76    c =  s.charAt(i++);
77    if(c == 'n')      c = '\n';
78    else if(c == 'r') c = '\r';
79    else if(c == 't') c = '\t';
80    else if(c == 'f') c = '\f';
81    else if(c == '\b') c = '\b';
82    else if(c == '\"') c = '\"';
83    else if(c == '\'') c = '\'';
84    else if(c == '\\') c = '\\';
85      }
86      sbuf.append(c);
87    }
88    return sbuf.toString();
89  }
90*/
91
92    /**
93    * Read a predefined var.
94    *
95    * It returns a value referenced by <var>$key</var> using this search criteria:
96    * - if <var>$key</var> is a constant then return it. Else
97    * - if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
98    * - return <var>$def</var>.
99    *
100    * @param string $key The key to search for.
101    * @param string $def The default value to return.
102    * @return string    the string value of the system property, or the default
103    *                   value if there is no property with that key.
104    *
105    * @static
106    */
107    function getSystemProperty($key, $def)
108    {
109        LoggerLog::debug("LoggerOptionConverter::getSystemProperty():key=[{$key}]:def=[{$def}].");
110
111        if (defined($key)) {
112            return (string)constant($key);
113        } elseif (isset($_ENV[$key])) {
114            return (string)$_ENV[$key];
115        } else {
116            return $def;
117        }
118    }
119
120    /**
121     * If <var>$value</var> is <i>true</i>, then <i>true</i> is
122     * returned. If <var>$value</var> is <i>false</i>, then
123     * <i>true</i> is returned. Otherwise, <var>$default</var> is
124     * returned.
125     *
126     * <p>Case of value is unimportant.</p>
127     *
128     * @param string $value
129     * @param boolean $default
130     * @return boolean
131     *
132     * @static
133     */
134    function toBoolean($value, $default)
135    {
136        if($value === null)
137            return $default;
138        if ($value == 1)
139            return true;
140        $trimmedVal = strtolower(trim($value));
141        if ("true" == $trimmedVal or "yes" == $trimmedVal)
142            return true;
143        if ("false" == $trimmedVal)
144            return false;
145        return $default;
146    }
147
148    /**
149     * @param string $value
150     * @param integer $default
151     * @return integer
152     * @static
153     */
154    function toInt($value, $default)
155    {
156        $value = trim($value);
157        if (is_numeric($value)) {
158            return (int)$value;
159        } else {
160            return $default;
161        }
162    }
163
164    /**
165     * Converts a standard or custom priority level to a Level
166     * object.
167     *
168     * <p> If <var>$value</var> is of form "<b>level#full_file_classname</b>",
169     * where <i>full_file_classname</i> means the class filename with path
170     * but without php extension, then the specified class' <i>toLevel()</i> method
171     * is called to process the specified level string; if no '#'
172     * character is present, then the default {@link LoggerLevel}
173     * class is used to process the level value.</p>
174     *
175     * <p>As a special case, if the <var>$value</var> parameter is
176     * equal to the string "NULL", then the value <i>null</i> will
177     * be returned.</p>
178     *
179     * <p>If any error occurs while converting the value to a level,
180     * the <var>$defaultValue</var> parameter, which may be
181     * <i>null</i>, is returned.</p>
182     *
183     * <p>Case of <var>$value</var> is insignificant for the level level, but is
184     * significant for the class name part, if present.</p>
185     *
186     * @param string $value
187     * @param LoggerLevel $defaultValue
188     * @return LoggerLevel a {@link LoggerLevel} or null
189     * @static
190     */
191    function toLevel($value, $defaultValue)
192    {
193        if($value === null)
194            return $defaultValue;
195
196        $hashIndex = strpos($value, '#');
197        if ($hashIndex === false) {
198            if("NULL" == strtoupper($value)) {
199                return null;
200            } else {
201                // no class name specified : use standard Level class
202                return LoggerLevel::toLevel($value, $defaultValue);
203            }
204        }
205
206        $result = $defaultValue;
207
208        $clazz = substr($value, ($hashIndex + 1));
209        $levelName = substr($value, 0, $hashIndex);
210
211        // This is degenerate case but you never know.
212        if("NULL" == strtoupper($levelName)) {
213            return null;
214        }
215
216        LoggerLog::debug("LoggerOptionConverter::toLevel():class=[{$clazz}]:pri=[{$levelName}]");
217
218        if (!class_exists($clazz))
219            @include_once("{$clazz}.php");
220
221        $clazz = basename($clazz);
222
223        if (class_exists($clazz)) {
224            $result = @call_user_func(array($clazz, 'toLevel'), $value, $defaultValue);
225            if (!is_a($result, 'loggerlevel')) {
226                LoggerLog::debug("LoggerOptionConverter::toLevel():class=[{$clazz}] cannot call toLevel(). Returning default.");           
227                $result = $defaultValue;
228            }
229        } else {
230            LoggerLog::warn("LoggerOptionConverter::toLevel() class '{$clazz}' doesnt exists.");
231        }
232        return $result;
233    }
234
235    /**
236     * @param string $value
237     * @param float $default
238     * @return float
239     *
240     * @static
241     */
242    function toFileSize($value, $default)
243    {
244        if ($value === null)
245            return $default;
246
247        $s = strtoupper(trim($value));
248        $multiplier = (float)1;
249        if(($index = strpos($s, 'KB')) !== false) {
250            $multiplier = 1024;
251            $s = substr($s, 0, $index);
252        } elseif(($index = strpos($s, 'MB')) !== false) {
253            $multiplier = 1024 * 1024;
254            $s = substr($s, 0, $index);
255        } elseif(($index = strpos($s, 'GB')) !== false) {
256            $multiplier = 1024 * 1024 * 1024;
257            $s = substr($s, 0, $index);
258        }
259        if(is_numeric($s)) {
260            return (float)$s * $multiplier;
261        } else {
262            LoggerLog::warn("LoggerOptionConverter::toFileSize() [{$s}] is not in proper form.");
263        }
264        return $default;
265    }
266
267    /**
268     * Find the value corresponding to <var>$key</var> in
269     * <var>$props</var>. Then perform variable substitution on the
270     * found value.
271     *
272     * @param string $key
273     * @param array $props
274     * @return string
275     *
276     * @static
277     */
278    function findAndSubst($key, $props)
279    {
280        $value = @$props[$key];
281        if(empty($value)) {
282            return null;
283        }
284        return LoggerOptionConverter::substVars($value, $props);
285    }
286
287    /**
288     * Perform variable substitution in string <var>$val</var> from the
289     * values of keys found with the {@link getSystemProperty()} method.
290     *
291     * <p>The variable substitution delimeters are <b>${</b> and <b>}</b>.
292     *
293     * <p>For example, if the "MY_CONSTANT" contains "value", then
294     * the call
295     * <code>
296     * $s = LoggerOptionConverter::substituteVars("Value of key is ${MY_CONSTANT}.");
297     * </code>
298     * will set the variable <i>$s</i> to "Value of key is value.".</p>
299     *
300     * <p>If no value could be found for the specified key, then the
301     * <var>$props</var> parameter is searched, if the value could not
302     * be found there, then substitution defaults to the empty string.</p>
303     *
304     * <p>For example, if {@link getSystemProperty()} cannot find any value for the key
305     * "inexistentKey", then the call
306     * <code>
307     * $s = LoggerOptionConverter::substVars("Value of inexistentKey is [${inexistentKey}]");
308     * </code>
309     * will set <var>$s</var> to "Value of inexistentKey is []".</p>
310     *
311     * <p>A warn is thrown if <var>$val</var> contains a start delimeter "${"
312     * which is not balanced by a stop delimeter "}" and an empty string is returned.</p>
313     *
314     * @log4j-author Avy Sharell
315     *
316     * @param string $val The string on which variable substitution is performed.
317     * @param array $props
318     * @return string
319     *
320     * @static
321     */
322    function substVars($val, $props = null)
323    {
324        LoggerLog::debug("LoggerOptionConverter::substVars():val=[{$val}]");
325       
326        $sbuf = '';
327        $i = 0;
328        while(true) {
329            $j = strpos($val, LOG4PHP_OPTION_CONVERTER_DELIM_START, $i);
330            if ($j === false) {
331                LoggerLog::debug("LoggerOptionConverter::substVars() no more variables");
332                // no more variables
333                if ($i == 0) { // this is a simple string
334                    LoggerLog::debug("LoggerOptionConverter::substVars() simple string");
335                    return $val;
336                } else { // add the tail string which contails no variables and return the result.
337                    $sbuf .= substr($val, $i);
338                    LoggerLog::debug("LoggerOptionConverter::substVars():sbuf=[{$sbuf}]. Returning sbuf");                   
339                    return $sbuf;
340                }
341            } else {
342           
343                $sbuf .= substr($val, $i, $j-$i);
344                LoggerLog::debug("LoggerOptionConverter::substVars():sbuf=[{$sbuf}]:i={$i}:j={$j}.");
345                $k = strpos($val, LOG4PHP_OPTION_CONVERTER_DELIM_STOP, $j);
346                if ($k === false) {
347                    LoggerLog::warn(
348                        "LoggerOptionConverter::substVars() " .
349                        "'{$val}' has no closing brace. Opening brace at position {$j}."
350                    );
351                    return '';
352                } else {
353                    $j += LOG4PHP_OPTION_CONVERTER_DELIM_START_LEN;
354                    $key = substr($val, $j, $k - $j);
355                    // first try in System properties
356                    $replacement = LoggerOptionConverter::getSystemProperty($key, null);
357                    // then try props parameter
358                    if($replacement == null and $props !== null) {
359                        $replacement = @$props[$key];
360                    }
361
362                    if(!empty($replacement)) {
363                        // Do variable substitution on the replacement string
364                        // such that we can solve "Hello ${x2}" as "Hello p1"
365                        // the where the properties are
366                        // x1=p1
367                        // x2=${x1}
368                        $recursiveReplacement = LoggerOptionConverter::substVars($replacement, $props);
369                        $sbuf .= $recursiveReplacement;
370                    }
371                    $i = $k + LOG4PHP_OPTION_CONVERTER_DELIM_STOP_LEN;
372                }
373            }
374        }
375    }
376
377}
378?>
Note: See TracBrowser for help on using the repository browser.