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