UnderstandFormatter::convertDatetime()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 14
rs 9.4286
cc 3
eloc 5
nc 2
nop 1
1
<?php namespace UnderstandMonolog\Formatter;
2
3
use Monolog\Formatter\FormatterInterface;
4
5
class UnderstandFormatter implements FormatterInterface
6
{
7
8
    /**
9
     * Format event
10
     *
11
     * @param array $record
12
     * @return string
13
     */
14
    public function format(array $record)
15
    {
16
        $recordWithTimestamp = $this->convertDatetime($record);
17
18
        return json_encode($recordWithTimestamp);
19
    }
20
21
    /**
22
     * Format batch of events
23
     *
24
     * @param array $records
25
     * @return string
26
     */
27
    public function formatBatch(array $records)
28
    {
29
        $formatted = [];
30
31
        foreach($records as $record)
32
        {
33
            $formatted[] = $this->convertDatetime($record);
34
        }
35
36
        return json_encode($formatted);
37
    }
38
39
    /**
40
     * Convert datetime to _timestamp format
41
     *
42
     * @param array $record
43
     * @return array
44
     */
45
    protected function convertDatetime(array $record)
46
    {
47
        if (isset($record['datetime']) && $record['datetime'] instanceof \DateTime)
48
        {
49
            // U - Seconds since the Unix Epoch
50
            // u - Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000
51
            // http://php.net/manual/en/function.date.php
52
            $record['timestamp'] = intval(round((float)$record['datetime']->format('U.u') * 1000));
53
54
            unset($record['datetime']);
55
        }
56
57
        return $record;
58
    }
59
}