DatabaseConfigFile::createDirIfNeeded()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
namespace Queryr\Replicator;
4
5
use RuntimeException;
6
7
/**
8
 * @licence GNU GPL v2+
9
 * @author Jeroen De Dauw < [email protected] >
10
 */
11
class DatabaseConfigFile {
12
13
	private $configDir;
14
	private $configPath;
15
16
	public static function newInstance() {
17
		return new self();
18
	}
19
20
	private function __construct() {
21
		$this->configDir = __DIR__ . '/../config/';
22
		$this->configPath = $this->configDir . 'db.json';
23
	}
24
25
	public function write( array $config ) {
26
		$this->createDirIfNeeded();
27
28
		$writeResult = @file_put_contents(
29
			$this->configPath,
30
			json_encode( $config, JSON_PRETTY_PRINT )
31
		);
32
33
		if ( $writeResult === false ) {
34
			throw new RuntimeException( 'Could not write the config file' );
35
		}
36
	}
37
38
	private function createDirIfNeeded() {
39
		if ( !is_dir( $this->configDir ) ) {
40
			$success = @mkdir( $this->configDir );
41
42
			if ( !$success ) {
43
				throw new RuntimeException( 'Could create the config directory' );
44
			}
45
		}
46
	}
47
48
	/**
49
	 * @throws RuntimeException
50
	 */
51
	public function read(): array {
52
		$configJson = @file_get_contents( $this->configPath );
53
54
		if ( $configJson === false ) {
55
			throw new RuntimeException( 'Could not read the config file' );
56
		}
57
58
		return json_decode( $configJson, true );
59
	}
60
61
}
62
63