Stream::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
ccs 10
cts 10
cp 1
rs 9.7998
cc 3
nc 4
nop 2
crap 3
1
<?php
2
3
/**
4
 * This file is part of the Apix Project.
5
 *
6
 * (c) Franck Cassedanne <franck at ouarz.net>
7
 *
8
 * @license http://opensource.org/licenses/BSD-3-Clause  New BSD License
9
 */
10
11
namespace Apix\Log\Logger;
12
13
use Psr\Log\InvalidArgumentException;
14
use Apix\Log\LogEntry;
15
16
/**
17
 * Stream log wrapper.
18
 *
19
 * @author Franck Cassedanne <franck at ouarz.net>
20
 */
21
class Stream extends AbstractLogger implements LoggerInterface
22
{
23
24
    /**
25
     * Holds the stream.
26
     * @var resource
27
     */
28
    protected $stream;
29
30
    /**
31
     * Constructor.
32
     *
33
     * @param  resource|string $stream The stream to append to.
34
     * @throws InvalidArgumentException If the stream cannot be created/opened.
35
     */
36 180
    public function __construct($stream = 'php://stdout', $mode = 'a')
37
    {
38 180
        if (!is_resource($stream)) {
39 8
            $stream = @fopen($stream, $mode);
40 2
        }
41
42 180
        if (!is_resource($stream)) {
43 4
            throw new InvalidArgumentException(sprintf(
44 4
                'The stream "%s" cannot be created or opened', $stream
45 1
            ));
46
        }
47
48 180
        $this->stream = $stream;
49 45
    }
50
51
    /**
52
     * {@inheritDoc}
53
     */
54 168
    public function write(LogEntry $log)
55
    {
56 168
        if (!is_resource($this->stream)) {
57 4
            throw new \LogicException(
58 3
                'The stream resource has been __destruct() too early'
59 1
            );
60
        }
61 164
        return (bool) fwrite($this->stream, $log . $log->formatter->separator);
62
    }
63
64
    /**
65
     * {@inheritDoc}
66
     */
67 180
    public function close()
68
    {
69 180
        if (is_resource($this->stream)) {
70 180
            fclose($this->stream);
71 45
        }
72 45
    }
73
74
}