4
4
5
5
namespace Jfcherng \Diff \Utility ;
6
6
7
- use Jfcherng \Diff \Exception \FileNotFoundException ;
8
-
9
7
final class Language
10
8
{
11
9
/**
@@ -22,9 +20,6 @@ final class Language
22
20
* The constructor.
23
21
*
24
22
* @param string|string[] $langOrTrans the language string or translations array
25
- *
26
- * @throws \InvalidArgumentException
27
- * @throws FileNotFoundException language file not found
28
23
*/
29
24
public function __construct ($ langOrTrans = 'eng ' )
30
25
{
@@ -37,7 +32,6 @@ public function __construct($langOrTrans = 'eng')
37
32
* @param string|string[] $langOrTrans the language string or translations array
38
33
*
39
34
* @throws \InvalidArgumentException
40
- * @throws FileNotFoundException language file not found
41
35
*
42
36
* @return self
43
37
*/
@@ -83,19 +77,24 @@ public function getTranslations(): array
83
77
*
84
78
* @param string $language the language
85
79
*
86
- * @throws FileNotFoundException language file not found
80
+ * @throws \Exception fail to decode the JSON file
81
+ * @throws \LogicException path is a directory
82
+ * @throws \RuntimeException path cannot be opened
87
83
*
88
84
* @return string[]
89
85
*/
90
86
public function getTranslationsByLanguage (string $ language ): array
91
87
{
92
- $ file = __DIR__ . "/../languages/ {$ language }.json " ;
88
+ $ filePath = __DIR__ . "/../languages/ {$ language }.json " ;
89
+ $ file = new \SplFileObject ($ filePath , 'r ' );
90
+ $ fileContent = $ file ->fread ($ file ->getSize ());
93
91
94
- if (!\is_file ($ file )) {
95
- throw new FileNotFoundException ($ file );
92
+ /** @todo PHP ^7.3 JSON_THROW_ON_ERROR */
93
+ if (($ decoded = \json_decode ($ fileContent , true )) === null ) {
94
+ throw new \Exception ("Fail to decode JSON file: {$ filePath }" );
96
95
}
97
96
98
- return \json_decode ( \file_get_contents ( $ file ), true ) ;
97
+ return $ decoded ;
99
98
}
100
99
101
100
/**
@@ -115,8 +114,6 @@ public function translate(string $text): string
115
114
*
116
115
* @param string $language the language name
117
116
*
118
- * @throws FileNotFoundException language file not found
119
- *
120
117
* @return self
121
118
*/
122
119
private function setLanguage (string $ language ): self
0 commit comments