Passed
Push — master ( b6d533...ae6d1d )
by Jay
03:45
created

CsvHandler::streamWrite()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6.2163

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 11
cp 0.8182
rs 9.1111
c 0
b 0
f 0
cc 6
nc 4
nop 2
crap 6.2163
1
<?php
2
3
namespace FemtoPixel\Monolog\Handler;
4
5
use Monolog\Formatter\FormatterInterface;
6
use Monolog\Formatter\LineFormatter;
7
use Monolog\Formatter\NormalizerFormatter;
8
use Monolog\Handler\StreamHandler;
9
10
/**
11
 * Stores to a csv file
12
 *
13
 * Can be used to store big loads to physical files and import them later into another system that can handle CSV
14
 *
15
 * @author Jay MOULIN <[email protected]>
16
 */
17
class CsvHandler extends StreamHandler
18
{
19
    const DELIMITER = ',';
20
    const ENCLOSURE = '\'';
21
    const ESCAPE_CHAR = '\\';
22
23
    /**
24
     * @inheritdoc
25
     */
26 2
    protected function streamWrite($stream, array $record): void
27
    {
28 2
        if (is_array($record['formatted'])) {
29 1
            foreach ($record['formatted'] as $key => $info) {
30 1
                if (is_array($info)) {
31 1
                    $record['formatted'][$key] = json_encode($info);
32
                }
33
            }
34
        }
35 2
        $formatted = (array)$record['formatted'];
36 2
        if (version_compare(PHP_VERSION, '5.5.4', '>=') && !defined('HHVM_VERSION')) {
37 2
            fputcsv($stream, $formatted, static::DELIMITER, static::ENCLOSURE, static::ESCAPE_CHAR);
38 2
            return;
39
        }
40
        fputcsv($stream, $formatted, static::DELIMITER, static::ENCLOSURE);
41
    }
42
43
    /**
44
     * Gets the default formatter.
45
     *
46
     * Overwrite this if the LineFormatter is not a good default for your handler.
47
     */
48
    protected function getDefaultFormatter(): FormatterInterface
49
    {
50
        return new NormalizerFormatter();
51
    }
52
}
53