Completed
Pull Request — master (#84)
by Pavel
08:52
created

Message::logLevelToSyslog()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.105

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 20
ccs 12
cts 14
cp 0.8571
rs 8.8571
c 1
b 0
f 0
cc 6
eloc 12
nc 5
nop 1
crap 6.105
1
<?php
2
3
/*
4
 * This file is part of the php-gelf package.
5
 *
6
 * (c) Benjamin Zikarsky <http://benjamin-zikarsky.de>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Gelf;
13
14
use Psr\Log\LogLevel;
15
use RuntimeException;
16
17
/**
18
 * A message complying to the GELF standard
19
 * <https://github.com/Graylog2/graylog2-docs/wiki/GELF>
20
 *
21
 * @author Benjamin Zikarsky <[email protected]>
22
 */
23
class Message implements MessageInterface
24
{
25
26
    protected $host;
27
    protected $shortMessage;
28
    protected $fullMessage;
29
    protected $timestamp;
30
    protected $level;
31
    protected $facility;
32
    protected $file;
33
    protected $line;
34
    protected $additionals = array();
35
    protected $version;
36
37
    /**
38
     * A list of the PSR LogLevel constants which is also a mapping of
39
     * syslog code to psr-value
40
     *
41
     * @var array
42
     */
43
    private static $psrLevels = array(
44
        LogLevel::EMERGENCY,    // 0
45
        LogLevel::ALERT,        // 1
46
        LogLevel::CRITICAL,     // 2
47
        LogLevel::ERROR,        // 3
48
        LogLevel::WARNING,      // 4
49
        LogLevel::NOTICE,       // 5
50
        LogLevel::INFO,         // 6
51
        LogLevel::DEBUG         // 7
52
    );
53
54
    /**
55
     * Creates a new message
56
     *
57
     * Populates timestamp and host with sane default values
58
     */
59 62
    public function __construct()
60
    {
61 62
        $this->timestamp = microtime(true);
62 62
        $this->host = gethostname();
63 62
        $this->level = 1; //ALERT
64 62
        $this->version = "1.0";
65 62
    }
66
67
    /**
68
     * Trys to convert a given log-level (psr or syslog) to
69
     * the psr representation
70
     *
71
     * @param  mixed  $level
72
     * @return string
73
     */
74 4
    final public static function logLevelToPsr($level)
75
    {
76 4
        $origLevel = $level;
77
78 4
        if (is_numeric($level)) {
79 3
            $level = intval($level);
80 3
            if (isset(self::$psrLevels[$level])) {
81 2
                return self::$psrLevels[$level];
82
            }
83 3
        } elseif (is_string($level)) {
84 2
            $level = strtolower($level);
85 2
            if (in_array($level, self::$psrLevels)) {
86 1
                return $level;
87
            }
88 1
        }
89
90 2
        throw new RuntimeException(
91 2
            sprintf("Cannot convert log-level '%s' to psr-style", $origLevel)
92 2
        );
93
    }
94
95
    /**
96
     * Trys to convert a given log-level (psr or syslog) to
97
     * the syslog representation
98
     *
99
     * @param mxied
100
     * @return integer
101
     */
102 20
    final public static function logLevelToSyslog($level)
103
    {
104 20
        $origLevel = $level;
105
106 20
        if (is_numeric($level)) {
107 4
            $level = intval($level);
108 4
            if ($level < 8 && $level > -1) {
109 3
                return $level;
110
            }
111 18
        } elseif (is_string($level)) {
112 17
            $level = strtolower($level);
113 17
            if (false !== $level = array_search($level, $psrLevels)) {
0 ignored issues
show
Bug introduced by
The variable $psrLevels does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
114
                return $level;
115
            }
116
        }
117
118 1
        throw new RuntimeException(
119 1
            sprintf("Cannot convert log-level '%s' to syslog-style", $origLevel)
120 1
        );
121
    }
122
123 3
    public function getVersion()
124
    {
125 3
        return $this->version;
126
    }
127
128 2
    public function setVersion($version)
129
    {
130 2
        $this->version = $version;
131
        
132 2
        return $this;
133
    }
134
135 3
    public function getHost()
136
    {
137 3
        return $this->host;
138
    }
139
140 2
    public function setHost($host)
141
    {
142 2
        $this->host = $host;
143
144 2
        return $this;
145
    }
146
147 3
    public function getShortMessage()
148
    {
149 3
        return $this->shortMessage;
150
    }
151
152 3
    public function setShortMessage($shortMessage)
153
    {
154 3
        $this->shortMessage = $shortMessage;
155
156 3
        return $this;
157
    }
158
159 3
    public function getFullMessage()
160
    {
161 3
        return $this->fullMessage;
162
    }
163
164 2
    public function setFullMessage($fullMessage)
165
    {
166 2
        $this->fullMessage = $fullMessage;
167
168 2
        return $this;
169
    }
170
171 4
    public function getTimestamp()
172
    {
173 4
        return (float) $this->timestamp;
174
    }
175
176 3
    public function setTimestamp($timestamp)
177
    {
178 3
        if ($timestamp instanceof \DateTime || $timestamp instanceof \DateTimeInterface) {
179 2
            $timestamp = $timestamp->format("U.u");
180 2
        }
181
182 3
        $this->timestamp = (float) $timestamp;
183
184 3
        return $this;
185
    }
186
187 1
    public function getLevel()
188
    {
189 1
        return self::logLevelToPsr($this->level);
190
    }
191
192 3
    public function getSyslogLevel()
193
    {
194 3
        return self::logLevelToSyslog($this->level);
195
    }
196
197 18
    public function setLevel($level)
198
    {
199 18
        $this->level = self::logLevelToSyslog($level);
200
201 1
        return $this;
202
    }
203
204 3
    public function getFacility()
205
    {
206 3
        return $this->facility;
207
    }
208
209 2
    public function setFacility($facility)
210
    {
211 2
        $this->facility = $facility;
212
213 2
        return $this;
214
    }
215
216 3
    public function getFile()
217
    {
218 3
        return $this->file;
219
    }
220
221 3
    public function setFile($file)
222
    {
223 3
        $this->file = $file;
224
225 3
        return $this;
226
    }
227
228 3
    public function getLine()
229
    {
230 3
        return $this->line;
231
    }
232
233 2
    public function setLine($line)
234
    {
235 2
        $this->line = $line;
236
237 2
        return $this;
238
    }
239
240 2
    public function getAdditional($key)
241
    {
242 2
        if (!isset($this->additionals[$key])) {
243 1
            throw new RuntimeException(
244 1
                sprintf("Additional key '%s' is not defined", $key)
245 1
            );
246
        }
247
248 1
        return $this->additionals[$key];
249
    }
250
251 1
    public function hasAdditional($key)
252
    {
253 1
        return isset($this->additionals[$key]);
254
    }
255
256 5
    public function setAdditional($key, $value)
257
    {
258 5
        if (!$key) {
259 1
            throw new RuntimeException("Additional field key cannot be empty");
260
        }
261
262 4
        $this->additionals[$key] = $value;
263
264 4
        return $this;
265
    }
266
267 3
    public function getAllAdditionals()
268
    {
269 3
        return $this->additionals;
270
    }
271
272 2
    public function toArray()
273
    {
274
        $message = array(
275 2
            'version'       => $this->getVersion(),
276 2
            'host'          => $this->getHost(),
277 2
            'short_message' => $this->getShortMessage(),
278 2
            'full_message'  => $this->getFullMessage(),
279 2
            'level'         => $this->getSyslogLevel(),
280 2
            'timestamp'     => $this->getTimestamp(),
281 2
            'facility'      => $this->getFacility(),
282 2
            'file'          => $this->getFile(),
283 2
            'line'          => $this->getLine()
284 2
        );
285
286
        // Transform 1.1 deprecated fields to additionals
287
        // Will be refactored for 2.0, see #23
288 2
        if ($this->getVersion() == "1.1") {
289 1
            foreach (array('line', 'facility', 'file') as $idx) {
290 1
                $message["_" . $idx] = $message[$idx];
291 1
                unset($message[$idx]);
292 1
            }
293 1
        }
294
295
        // add additionals
296 2
        foreach ($this->getAllAdditionals() as $key => $value) {
297 2
            $message["_" . $key] = $value;
298 2
        }
299
300
        // return after filtering empty strings and null values
301 2
        return array_filter($message, function ($message) {
302 2
            return is_bool($message) || strlen($message);
303 2
        });
304
    }
305
}
306