StreamHandler::openStream()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Logger
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Logger\Handler;
13
14
use Phoole\Logger\Entry\LogEntryInterface;
15
use Phoole\Logger\Formatter\FormatterInterface;
16
17
/**
18
 * @package Phoole\Logger
19
 */
20
class StreamHandler extends HandlerAbstract
21
{
22
    /**
23
     * @var resource
24
     */
25
    protected $stream;
26
27
    /**
28
     * @param  string|resource    $stream
29
     * @param  FormatterInterface $formatter
30
     */
31
    public function __construct($stream, ?FormatterInterface $formatter = NULL)
32
    {
33
        $this->stream = $this->openStream($stream);
34
        parent::__construct($formatter);
35
    }
36
37
    /**
38
     * Open stream for writing
39
     *
40
     * @param  string|resource $path
41
     * @return resource
42
     * @throws \LogicException if open failure
43
     */
44
    protected function openStream($path)
45
    {
46
        if (is_string($path)) {
47
            if (FALSE === strpos($path, '://')) {
48
                $path = 'file://' . $path;
49
            }
50
            return fopen($path, 'a');
51
        }
52
        if (is_resource($path)) {
53
            return $path;
54
        }
55
        throw new \LogicException("failed to open stream");
56
    }
57
58
    /**
59
     * close the stream
60
     */
61
    protected function close()
62
    {
63
        if ($this->stream) {
64
            fclose($this->stream);
65
            $this->stream = FALSE;
0 ignored issues
show
Documentation Bug introduced by
It seems like FALSE of type false is incompatible with the declared type resource of property $stream.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
66
        }
67
    }
68
69
    /**
70
     * {@inheritDoc}
71
     */
72
    protected function write(LogEntryInterface $entry)
73
    {
74
        if ($this->stream) {
75
            $msg = $this->getFormatter()->format($entry);
76
            flock($this->stream, LOCK_EX);
77
            fwrite($this->stream, $msg);
78
            flock($this->stream, LOCK_UN);
79
        }
80
    }
81
}