|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* eduVPN - End-user friendly VPN. |
|
5
|
|
|
* |
|
6
|
|
|
* Copyright: 2016-2017, The Commons Conservancy eduVPN Programme |
|
7
|
|
|
* SPDX-License-Identifier: AGPL-3.0+ |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace SURFnet\VPN\Common; |
|
11
|
|
|
|
|
12
|
|
|
use RuntimeException; |
|
13
|
|
|
|
|
14
|
|
|
class FileIO |
|
15
|
|
|
{ |
|
16
|
|
|
public static function readFile($filePath) |
|
17
|
|
|
{ |
|
18
|
|
|
if (false === $fileData = @file_get_contents($filePath)) { |
|
19
|
|
|
throw new RuntimeException(sprintf('unable to read file "%s"', $filePath)); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
return $fileData; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function readJsonFile($filePath) |
|
26
|
|
|
{ |
|
27
|
|
|
$fileData = self::readFile($filePath); |
|
28
|
|
|
$jsonData = json_decode($fileData, true); |
|
29
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) { |
|
30
|
|
|
throw new RuntimeException(sprintf('unable to decode JSON from file "%s"', $filePath)); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return $jsonData; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public static function writeFile($filePath, $fileData, $mode = 0600) |
|
37
|
|
|
{ |
|
38
|
|
|
if (false === @file_put_contents($filePath, $fileData)) { |
|
39
|
|
|
throw new RuntimeException(sprintf('unable to write file "%s"', $filePath)); |
|
40
|
|
|
} |
|
41
|
|
|
if (false === chmod($filePath, $mode)) { |
|
42
|
|
|
throw new RuntimeException(sprintf('unable to set permissions on file "%s"', $filePath)); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public static function writeJsonFile($filePath, $fileJsonData, $mode = 0600) |
|
47
|
|
|
{ |
|
48
|
|
|
$fileData = json_encode($fileJsonData); |
|
49
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) { |
|
50
|
|
|
throw new RuntimeException(sprintf('unable to encode JSON for file "%s"', $filePath)); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
self::writeFile($filePath, $fileData, $mode); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public static function deleteFile($filePath) |
|
57
|
|
|
{ |
|
58
|
|
|
if (false === @unlink($filePath)) { |
|
59
|
|
|
throw new RuntimeException(sprintf('unable to delete file "%s"', $filePath)); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public static function createDir($dirPath, $mode = 0711) |
|
64
|
|
|
{ |
|
65
|
|
|
if (!@file_exists($dirPath)) { |
|
66
|
|
|
if (false === @mkdir($dirPath, $mode, true)) { |
|
67
|
|
|
throw new RuntimeException(sprintf('unable to create directory "%s"', $dirPath)); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|