JsonService::read()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 15.2377

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
ccs 1
cts 9
cp 0.1111
cc 4
eloc 11
nc 5
nop 1
crap 15.2377
1
<?php
2
namespace keeko\tools\services;
3
4
use keeko\tools\exceptions\JsonEmptyException;
5
use phootwork\file\File;
6
use phootwork\json\Json;
7
use phootwork\json\JsonException;
8
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
9
10
class JsonService extends AbstractService {
11
12
	/**
13
	 * Reads a file and decodes json
14
	 * 
15
	 * @param string $filename
16
	 * @throws FileNotFoundException
17
	 * @throws JsonEmptyException
18
	 * @throws \RuntimeException
19
	 * @return array
20 1
	 */
21
	public function read($filename) {
22
		if (!file_exists($filename)) {
23
			throw new FileNotFoundException(sprintf('%s not found', $filename));
24
		}
25
26
		try {
27
			$file = new File($filename);
28
			$json = Json::decode($file->read());
29
		} catch (JsonException $e) {
30
			throw new \RuntimeException(sprintf('Problem occured while decoding %s: %s', $filename, $e->getMessage()));
31
		}
32
		
33
		if ($json === null) {
34
			throw new JsonEmptyException(sprintf('%s is empty', $filename));
35
		}
36 1
		
37
		return $json;
38
	}
39
40
	/**
41
	 * Encodes contents to json and writes them into the given filename
42
	 * 
43
	 * @param string $filename
44
	 * @param array $contents
45 16
	 */
46 16
	public function write($filename, $contents) {
47 16
		$json = Json::encode($contents, Json::PRETTY_PRINT | Json::UNESCAPED_SLASHES);
48
		$json = str_replace('    ', "\t", $json);
49 16
50 16
		$file = new File($filename);
51 16
		if ($file->exists()) {
52 16
			$file->setMode(0755);
53
		}
54
		$file->write($json);
55
	}
56
}