LogFormatter   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 1
dl 0
loc 58
c 0
b 0
f 0
ccs 24
cts 24
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B interpolate() 0 21 9
A format() 0 9 1
1
<?php
2
3
/**
4
 * This file is part of the Apix Project.
5
 *
6
 * (c) Franck Cassedanne <franck at ouarz.net>
7
 *
8
 * @license http://opensource.org/licenses/BSD-3-Clause  New BSD License
9
 */
10
11
namespace Apix\Log;
12
13
/**
14
 * Standard log formatter.
15
 *
16
 * @author Franck Cassedanne <franck at ouarz.net>
17
 */
18
class LogFormatter implements LogFormatterInterface
19
{
20
21
    /**
22
     * Holds this log separator.
23
     * @var string
24
     */
25
    public $separator = PHP_EOL;
26
27
    /**
28
     * Interpolates context values into the message placeholders.
29
     *
30
     * Builds a replacement array with braces around the context keys.
31
     * It replaces {foo} with the value from $context['foo'].
32
     *
33
     * @param  string $message
34
     * @param  array  $context
35
     * @return string
36
     */
37 692
    public function interpolate($message, array $context = array())
38
    {        
39 692
        $replaces = array();
40 692
        foreach ($context as $key => $val) {
41 652
            if (is_bool($val)) {
42 80
                $val = '[bool: ' . (int) $val . ']';
43 604
            } elseif (is_null($val)
44 580
                || is_scalar($val)
45 580
                || ( is_object($val) && method_exists($val, '__toString') )
46 147
            ) {
47 364
                $val = (string) $val;
48 330
            } elseif (is_array($val) || is_object($val)) {
49 212
                $val = @json_encode($val);
50 53
            } else {
51 48
                $val = '[type: ' . gettype($val) . ']';
52
            }
53 652
            $replaces['{' . $key . '}'] = $val;
54 173
        }
55
56 692
        return strtr($message, $replaces);
57
    }
58
59
    /**
60
     * Formats the given log entry.
61
     *
62
     * @param  LogEntry $log The log entry to format.
63
     * @return string
64
     */
65 688
    public function format(LogEntry $log)
66
    {
67 688
        return sprintf(
68 688
            '[%s] %s %s',
69 688
            date('Y-m-d H:i:s', $log->timestamp),
70 688
            strtoupper($log->name),
71 688
            self::interpolate($log->message, $log->context)
72 172
        );
73
    }
74
75
}