@@ -25,34 +25,22 @@ class Json {
2525 *
2626 * @since 1.0.0
2727 *
28- * @param array $array → array to be converted to JSON file
29- * @param string $pathfile → path to the file
28+ * @param array $array → array to be converted to JSON
29+ * @param string $file → path to the file
3030 *
3131 * @throws JsonException → couldn't create file
3232 *
3333 * @return boolean true → if the file is created
3434 */
35- public static function arrayToFile ($ array , $ pathfile ) {
35+ public static function arrayToFile ($ array , $ file ) {
3636
37- $ path = str_replace (basename ($ pathfile ), '' , $ pathfile );
38-
39- if (!empty ($ path ) && !is_dir ($ path )) {
40-
41- mkdir ($ path , 0755 , true );
42- }
37+ self ::_createDirectory ($ file );
4338
4439 $ json = json_encode ($ array , JSON_PRETTY_PRINT );
4540
4641 $ json = self ::_jsonLastError () ? json_encode ($ json , 128 ) : $ json ;
47-
48- if (!$ file = fopen ($ pathfile , 'w+ ' )) {
4942
50- $ message = 'Could not create file in ' ;
51-
52- throw new JsonException ($ message . ' ' . $ pathfile , 605 );
53- }
54-
55- fwrite ($ file , $ json );
43+ self ::_saveFile ($ file , $ json );
5644
5745 return true ;
5846 }
@@ -70,7 +58,7 @@ public static function fileToArray($file) {
7058
7159 if (!is_file ($ file ) && !filter_var ($ file , FILTER_VALIDATE_URL )) {
7260
73- self ::arrayToFile ([], $ pathFile );
61+ self ::arrayToFile ([], $ file );
7462 }
7563
7664 $ jsonString = file_get_contents ($ file );
@@ -80,6 +68,54 @@ public static function fileToArray($file) {
8068 return self ::_jsonLastError () ?: $ jsonArray ;
8169 }
8270
71+ /**
72+ * Create directory recursively if it doesn't exist.
73+ *
74+ * @since 1.1.3
75+ *
76+ * @param string $file → path to the directory
77+ *
78+ * @throws JsonException → couldn't create directory
79+ *
80+ * @return void
81+ */
82+ private static function _createDirectory ($ file ) {
83+
84+ $ path = str_replace (basename ($ file ), '' , $ file );
85+
86+ if (!empty ($ path ) && !is_dir ($ path )) {
87+
88+ if (!mkdir ($ path , 0755 , true )) {
89+
90+ $ message = 'Could not create directory in ' ;
91+
92+ throw new JsonException ($ message . ' ' . $ path , 605 );
93+ }
94+ }
95+ }
96+
97+ /**
98+ * Create directory recursively.
99+ *
100+ * @since 1.1.3
101+ *
102+ * @param string $file → path to the file
103+ * @param string $json → json string
104+ *
105+ * @throws JsonException → couldn't create file
106+ *
107+ * @return void
108+ */
109+ private static function _saveFile ($ file , $ json ) {
110+
111+ if (file_put_contents ($ file , $ json ) === false ) {
112+
113+ $ message = 'Could not create file in ' ;
114+
115+ throw new JsonException ($ message . ' ' . $ file , 606 );
116+ }
117+ }
118+
83119 /**
84120 * Check for errors.
85121 *
0 commit comments