1616use Josantonius \Json \Exceptions \GetFileException ;
1717use Josantonius \Json \Exceptions \JsonErrorException ;
1818use Josantonius \Json \Exceptions \CreateFileException ;
19+ use Josantonius \Json \Exceptions \CreateDirectoryException ;
1920use Josantonius \Json \Exceptions \UnavailableMethodException ;
2021
2122/**
@@ -67,6 +68,7 @@ public function get(): array
6768 *
6869 * @throws CreateFileException if the file cannot be created.
6970 * @throws UnavailableMethodException if an unavailable method is accessed.
71+ * @throws CreateDirectoryException if the directory cannot be created.
7072 */
7173 public function set (array |object $ content = []): void
7274 {
@@ -107,11 +109,25 @@ public function push(array|object $content): array
107109 return $ data ;
108110 }
109111
112+ /**
113+ * Create directory if not exists.
114+ *
115+ * @throws CreateDirectoryException if the directory cannot be created.
116+ */
117+ private function createDirIfNotExists (): void
118+ {
119+ $ path = dirname ($ this ->filepath ) . DIRECTORY_SEPARATOR ;
120+ if (!is_dir ($ path ) && !@mkdir ($ path , 0777 , true )) {
121+ throw new CreateDirectoryException ($ path );
122+ }
123+ }
124+
110125 /**
111126 * Get the content of the JSON file or a remote JSON file.
112127 *
113- * @throws GetFileException if the file cannot be read.
114- * @throws JsonErrorException if the JSON has errors.
128+ * @throws GetFileException if the file cannot be read.
129+ * @throws JsonErrorException if the JSON has errors.
130+ * @throws CreateDirectoryException if the directory cannot be created.
115131 */
116132 private function getFileContents (): array
117133 {
@@ -137,6 +153,8 @@ private function saveToJsonFile(array|object $array): void
137153 {
138154 $ json = json_encode ($ array , JSON_PRETTY_PRINT );
139155
156+ $ this ->createDirIfNotExists ();
157+
140158 if (@file_put_contents ($ this ->filepath , $ json ) === false ) {
141159 throw new CreateFileException ($ this ->filepath );
142160 }
0 commit comments