Passed
Push — master ( 950b60...cce8f6 )
by Gabriel
28:13
created

StreamLogWriter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 96.3%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 45
ccs 26
cts 27
cp 0.963
rs 10
c 0
b 0
f 0
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A createPathIfNeeded() 0 7 3
A __construct() 0 2 1
A __destruct() 0 3 2
A write() 0 5 1
A openStreamIfNeeded() 0 8 3
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\BucketTesting\Logging;
6
7
/**
8
 * Writes log entries to a file stream, one per line
9
 */
10
class StreamLogWriter implements LogWriter {
11
12
	private $url;
13
	private $stream;
14
15 36
	public function __construct( string $url ) {
16 36
		$this->url = $url;
17 36
	}
18
19
	/**
20
	 * @param string $logEntry
21
	 * @throws LoggingError
22
	 */
23 36
	public function write( string $logEntry ) {
24 36
		$this->openStreamIfNeeded();
25 35
		fwrite(
26 35
			$this->stream,
27 35
			$logEntry . "\n"
28
		);
29 35
	}
30
31 36
	private function openStreamIfNeeded() {
32 36
		if ( $this->stream !== null ) {
33 2
			return;
34
		}
35 36
		$this->createPathIfNeeded();
36 35
		$this->stream = @fopen( $this->url, 'a' );
37 35
		if ( $this->stream === false ) {
38
			throw new LoggingError( 'Could not open ' . $this->url );
39
		}
40 35
	}
41
42 36
	private function createPathIfNeeded() {
43 36
		$path = dirname( $this->url );
44 36
		if ( file_exists( $path ) ) {
45 33
			return;
46
		}
47 3
		if ( !mkdir( $path, 0777, true ) ) {
48 1
			throw new LoggingError( 'Could not create directory ' . $path );
49
		}
50 2
	}
51
52 12
	public function __destruct() {
53 12
		if ( is_resource( $this->stream ) ) {
54 11
			@fclose( $this->stream );
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

54
			/** @scrutinizer ignore-unhandled */ @fclose( $this->stream );

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
55
		}
56 12
	}
57
58
}