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

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

#149 ロガークラス作成

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