Skip to content

Commit 0cc8365

Browse files
committed
feat: add new methods
Exists and filepath methods were added. The file is no longer created if it does not exist when the instance is created. The $content parameter of the set method is now optional and contains an empty array by default. Closes #22
1 parent 6cbd2bd commit 0cc8365

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/Json.php

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Josantonius\Json\Exceptions\GetFileException;
1717
use Josantonius\Json\Exceptions\JsonErrorException;
1818
use Josantonius\Json\Exceptions\CreateFileException;
19+
use Josantonius\Json\Exceptions\CreateDirectoryException;
1920
use 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

Comments
 (0)