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; |
|
|
|
|
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
|
|
|
} |
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..