Passed
Push — master ( 91afe8...ee7ada )
by Benjamin
10:47 queued 45s
created

Message::logLevelToSyslog()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 5
nop 1
dl 0
loc 19
ccs 14
cts 14
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
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 63
    public function __construct()
60
    {
61 63
        $this->timestamp = microtime(true);
62 63
        $this->host = gethostname();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
63 63
        $this->level = 1; //ALERT
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
64 63
        $this->version = "1.0";
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Coding Style Comprehensibility introduced by
The string literal 1.0 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
65 63
    }
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 5
    final public static function logLevelToPsr($level)
75
    {
76 5
        $origLevel = $level;
77
78 5
        if (is_numeric($level)) {
79 4
            $level = intval($level);
80 4
            if (isset(self::$psrLevels[$level])) {
81 3
                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 21
    final public static function logLevelToSyslog($level)
103
    {
104 21
        $origLevel = $level;
105
106 21
        if (is_numeric($level)) {
107 14
            $level = intval($level);
108 14
            if ($level < 8 && $level > -1) {
109 13
                return $level;
110
            }
111 18
        } elseif (is_string($level)) {
112 17
            $level = strtolower($level);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
113 17
            $syslogLevel = array_search($level, self::$psrLevels);
114 17
            if (false !== $syslogLevel) {
115 16
                return $syslogLevel;
116
            }
117 1
        }
118
119 2
        throw new RuntimeException(
120 2
            sprintf("Cannot convert log-level '%s' to syslog-style", $origLevel)
121 2
        );
122
    }
123
124 13
    public function getVersion()
125
    {
126 13
        return $this->version;
127
    }
128
129 3
    public function setVersion($version)
130
    {
131 3
        $this->version = $version;
132
133 3
        return $this;
134
    }
135
136 13
    public function getHost()
137
    {
138 13
        return $this->host;
139
    }
140
141 2
    public function setHost($host)
142
    {
143 2
        $this->host = $host;
144
145 2
        return $this;
146
    }
147
148 17
    public function getShortMessage()
149
    {
150 17
        return $this->shortMessage;
151
    }
152
153 17
    public function setShortMessage($shortMessage)
154
    {
155 17
        $this->shortMessage = $shortMessage;
156
157 17
        return $this;
158
    }
159
160 14
    public function getFullMessage()
161
    {
162 14
        return $this->fullMessage;
163
    }
164
165 3
    public function setFullMessage($fullMessage)
166
    {
167 3
        $this->fullMessage = $fullMessage;
168
169 3
        return $this;
170
    }
171
172 14
    public function getTimestamp()
173
    {
174 14
        return (float) $this->timestamp;
175
    }
176
177 3
    public function setTimestamp($timestamp)
178
    {
179 3
        if ($timestamp instanceof \DateTime || $timestamp instanceof \DateTimeInterface) {
180 2
            $timestamp = $timestamp->format("U.u");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal U.u does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
181 2
        }
182
183 3
        $this->timestamp = (float) $timestamp;
184
185 3
        return $this;
186
    }
187
188 2
    public function getLevel()
189
    {
190 2
        return self::logLevelToPsr($this->level);
191
    }
192
193 13
    public function getSyslogLevel()
194
    {
195 13
        return self::logLevelToSyslog($this->level);
196
    }
197
198 18
    public function setLevel($level)
199
    {
200 18
        $this->level = self::logLevelToSyslog($level);
201
202 16
        return $this;
203
    }
204
205 14
    public function getFacility()
206
    {
207 14
        return $this->facility;
208
    }
209
210 16
    public function setFacility($facility)
211
    {
212 16
        $this->facility = $facility;
213
214 16
        return $this;
215
    }
216
217 14
    public function getFile()
218
    {
219 14
        return $this->file;
220
    }
221
222 4
    public function setFile($file)
223
    {
224 4
        $this->file = $file;
225
226 4
        return $this;
227
    }
228
229 14
    public function getLine()
230
    {
231 14
        return $this->line;
232
    }
233
234 4
    public function setLine($line)
235
    {
236 4
        $this->line = $line;
237
238 4
        return $this;
239
    }
240
241 2
    public function getAdditional($key)
242
    {
243 2
        if (!isset($this->additionals[$key])) {
244 1
            throw new RuntimeException(
245 1
                sprintf("Additional key '%s' is not defined", $key)
246 1
            );
247
        }
248
249 1
        return $this->additionals[$key];
250
    }
251
252 1
    public function hasAdditional($key)
253
    {
254 1
        return isset($this->additionals[$key]);
255
    }
256
257 17
    public function setAdditional($key, $value)
258
    {
259 17
        if (!$key) {
260 1
            throw new RuntimeException("Additional field key cannot be empty");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Additional field key cannot be empty does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
261
        }
262
263 16
        $this->additionals[$key] = $value;
264
265 16
        return $this;
266
    }
267
268 14
    public function getAllAdditionals()
269
    {
270 14
        return $this->additionals;
271
    }
272
273 12
    public function toArray()
274
    {
275
        $message = array(
276 12
            'version'       => $this->getVersion(),
277 12
            'host'          => $this->getHost(),
278 12
            'short_message' => $this->getShortMessage(),
279 12
            'full_message'  => $this->getFullMessage(),
280 12
            'level'         => $this->getSyslogLevel(),
281 12
            'timestamp'     => $this->getTimestamp(),
282 12
            'facility'      => $this->getFacility(),
283 12
            'file'          => $this->getFile(),
284 12
            'line'          => $this->getLine()
285 12
        );
286
287
        // Transform 1.1 deprecated fields to additionals
288
        // Will be refactored for 2.0, see #23
289 12
        if ($this->getVersion() == "1.1") {
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal 1.1 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
290 1
            foreach (array('line', 'facility', 'file') as $idx) {
291 1
                $message["_" . $idx] = $message[$idx];
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal _ does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
292 1
                unset($message[$idx]);
293 1
            }
294 1
        }
295
296
        // add additionals
297 12
        foreach ($this->getAllAdditionals() as $key => $value) {
298 12
            $message["_" . $key] = $value;
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal _ does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
299 12
        }
300
301
        // return after filtering empty strings and null values
302 12
        return array_filter($message, function ($message) {
303 12
            return is_bool($message)
304 12
                || (is_string($message) && strlen($message))
305 12
                || !empty($message);
306 12
        });
307
    }
308
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
309