44
55namespace Jfcherng \Diff \Utility ;
66
7- use Jfcherng \Diff \Exception \FileNotFoundException ;
8-
97final class Language
108{
119 /**
@@ -22,9 +20,6 @@ final class Language
2220 * The constructor.
2321 *
2422 * @param string|string[] $langOrTrans the language string or translations array
25- *
26- * @throws \InvalidArgumentException
27- * @throws FileNotFoundException language file not found
2823 */
2924 public function __construct ($ langOrTrans = 'eng ' )
3025 {
@@ -37,7 +32,6 @@ public function __construct($langOrTrans = 'eng')
3732 * @param string|string[] $langOrTrans the language string or translations array
3833 *
3934 * @throws \InvalidArgumentException
40- * @throws FileNotFoundException language file not found
4135 *
4236 * @return self
4337 */
@@ -83,19 +77,24 @@ public function getTranslations(): array
8377 *
8478 * @param string $language the language
8579 *
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
8783 *
8884 * @return string[]
8985 */
9086 public function getTranslationsByLanguage (string $ language ): array
9187 {
92- $ file = __DIR__ . "/../languages/ {$ language }.json " ;
88+ $ filePath = __DIR__ . "/../languages/ {$ language }.json " ;
89+ $ file = new \SplFileObject ($ filePath , 'r ' );
90+ $ fileContent = $ file ->fread ($ file ->getSize ());
9391
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 }" );
9695 }
9796
98- return \json_decode ( \file_get_contents ( $ file ), true ) ;
97+ return $ decoded ;
9998 }
10099
101100 /**
@@ -115,8 +114,6 @@ public function translate(string $text): string
115114 *
116115 * @param string $language the language name
117116 *
118- * @throws FileNotFoundException language file not found
119- *
120117 * @return self
121118 */
122119 private function setLanguage (string $ language ): self
0 commit comments