Completed
Push — feature/logger ( 65a307 )
by
unknown
01:30
created

StreamWriter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 25%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 61
ccs 3
cts 12
cp 0.25
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addFormatter() 0 5 1
A write() 0 17 3
1
<?php
2
/**
3
 * @author Chris dePage <[email protected]>
4
 * @copyright 2009-2018 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Cli\Logger\Writer;
9
10
use Garden\Cli\Logger\Formatter\FormatterInterface;
11
12
/**
13
 * Log writer to output to a stream.
14
 */
15
class StreamWriter implements WriterInterface {
16
17
    /**
18
     * @var resource The stream resource.
19
     */
20
    protected $stream;
21
22
    /**
23
     * @var FormatterInterface[] An array of formatters.
24
     */
25
    protected $formatters = [];
26
27
    /**
28
     * StreamWriter constructor.
29
     *
30
     * @param string $stream The stream to write to.
31
     */
32 2
    public function __construct(string $stream) {
33 2
        $this->stream = fopen($stream, 'w');
34 2
    }
35
36
    /**
37
     * Add a formatter to be used by the writer.
38
     *
39
     * @param FormatterInterface $formatter A formatter to use for the writer.
40
     *
41
     * @return $this
42
     */
43
    public function addFormatter(FormatterInterface $formatter) {
44
        array_push($this->formatters, $formatter);
45
46
        return $this;
47
    }
48
49
    /**
50
     * Write the stream.
51
     *
52
     * @param int $timestamp The unix timestamp of the log.
53
     * @param string $logLevel The level of the message (e.g. INFO, SUCCESS, WARNING, ERROR).
54
     * @param string $message The message.
55
     * @param int $indentLevel The nesting level of the message.
56
     * @param float|null $duration The duration to add to the message.
57
     */
58
    public function write(int $timestamp, string $logLevel, string $message, int $indentLevel = 0, $duration = null) {
59
        // ensure our stream hasn't died
60
        if (feof($this->stream)) {
61
            // @codeCoverageIgnoreStart
62
            trigger_error('Called '.__CLASS__.'::write() but file handle was closed.', E_USER_WARNING);
63
            return;
64
            // @codeCoverageIgnoreEnd
65
        }
66
67
        // apply each of the formatters we've attached to this writer (will usually only be one)
68
        foreach($this->formatters as $formatter) {
69
            $message = $formatter->format($timestamp, $logLevel, $indentLevel, $message, $duration);
70
        }
71
72
        // write the message
73
        fwrite($this->stream, $message . PHP_EOL);
74
    }
75
}
76