-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONManager.php
383 lines (324 loc) · 13.5 KB
/
JSONManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<?php
/**
* Class JsonManager
*
* A PHP class to manage JSON data stored in a file.
*/
class JsonManager
{
/**
* Save data to the JSON file.
*
* @param string $path Path to the JSON file
* @param array $object Data object to save/update
* @param bool $isUpdate Flag indicating if data should be updated (default: false)
* @param mixed $location Specific location within the JSON structure to save/update (optional)
* @param string $keyToUpdate Key to search for when updating data (optional)
* @param mixed $valueToUpdate Value corresponding to $keyToUpdate to identify data to update (optional)
*
* @throws Exception If there is an error decoding JSON or saving JSON content
*/
public static function save($path, $object, $isUpdate = false, $keyToUpdate = null, $valueToUpdate = null)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '[]'; // Default to an empty JSON array if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg() . "\n" . var_dump);
}
// Ensure $data is an array
if (!is_array($data)) {
$data = [];
}
// Handle update if specified
if ($isUpdate && $keyToUpdate !== null && $valueToUpdate !== null) {
$found = false;
// Iterate through existing objects to find and update
foreach ($data as &$existingObject) {
if (isset($existingObject[$keyToUpdate]) && $existingObject[$keyToUpdate] == $valueToUpdate) {
$existingObject = array_merge($existingObject, $object); // Update existing object
$found = true;
break;
}
}
if (!$found) {
// If object not found, add it to the array
$data[] = $object;
}
} else {
// Add new object to data array
$data[] = $object;
}
// Encode updated data array to JSON
$newJson = json_encode($data, JSON_PRETTY_PRINT);
// Save updated JSON back to the file
if (!file_put_contents($path, $newJson)) {
throw new Exception("Error saving JSON to file: {$path}");
}
}
/**
* Retrieve all data from the JSON file.
*
* @param string $path Path to the JSON file
* @return array Array of all data objects
* @throws Exception If there is an error decoding JSON
*/
public static function getAll($path)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
return $data;
}
/**
* Find data in the JSON file by a specific key-value pair.
*
* @param string $path Path to the JSON file
* @param string $key Key to search for
* @param mixed $value Value corresponding to $key to search for
*
* @return array|null Array of matching data objects or null if not found
* @throws Exception If there is an error decoding JSON
*/
public static function findByKey($dataOrPath, $key, $value)
{
$data = [];
if (is_file($dataOrPath)) {
// Read the content of the JSON file
$fileContent = file_exists($dataOrPath) ? file_get_contents($dataOrPath) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
} else {
// Decode the JSON string to an associative array
$data = json_decode($dataOrPath, true);
}
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
$results = [];
// Function to recursively search for matching objects
$search = function($data) use (&$results, $key, $value, &$search) {
if (is_array($data)) {
foreach ($data as $item) {
if (is_array($item) || is_object($item)) {
// Recursively search nested arrays or objects
$search($item);
}
if (isset($item[$key]) && $item[$key] == $value) {
$results[] = $item;
}
}
} elseif (is_object($data)) {
// Convert object to array
$item = json_decode(json_encode($data), true);
if (isset($item[$key]) && $item[$key] == $value) {
$results[] = $item;
}
// Recursively search nested objects
$search($item);
}
};
// Start searching from the top level of $data
$search($data);
return $results;
}
/**
* Delete data from the JSON file based on a specific key-value pair.
*
* @param string $path Path to the JSON file
* @param string $key Key to search for
* @param mixed $value Value corresponding to $key to identify data to delete
*
* @throws Exception If there is an error decoding JSON or saving JSON content
*/
public static function deleteByKey($path, $key, $value)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
$updatedData = [];
// Remove matching objects
foreach ($data as $item) {
if (!(isset($item[$key]) && $item[$key] == $value)) {
$updatedData[] = $item;
}
}
// Encode updated data array to JSON
$newJson = json_encode($updatedData, JSON_PRETTY_PRINT);
// Save updated JSON back to the file
if (!file_put_contents($path, $newJson)) {
throw new Exception("Error saving JSON to file: {$path}");
}
}
/**
* Count the number of objects in the JSON file.
*
* @param string $path Path to the JSON file
* @return int Number of objects
* @throws Exception If there is an error decoding JSON
*/
public static function count($path)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
return count($data);
}
/**
* Sort data in the JSON file by a specific key.
*
* @param string $path Path to the JSON file
* @param string $key Key to sort by
*
* @return array Sorted array of data objects
* @throws Exception If there is an error decoding JSON
*/
public static function sortByKey($path, $key)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
// Sort data by specified key
usort($data, function ($a, $b) use ($key) {
return $a[$key] <=> $b[$key];
});
return $data;
}
/**
* Paginate the data in the JSON file.
*
* @param string $path Path to the JSON file
* @param int $perPage Number of items per page
* @param int $page Page number to retrieve
*
* @return array Array of data objects for the specified page
* @throws Exception If there is an error decoding JSON or invalid pagination parameters
*/
public static function paginate($path, $perPage, $page)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the JSON file content to an associative array
$data = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
if (!is_int($perPage) || !is_int($page) || $perPage <= 0 || $page <= 0) {
throw new Exception("Invalid pagination parameters");
}
$offset = ($page - 1) * $perPage;
// Paginate data
$paginatedData = array_slice($data, $offset, $perPage);
return $paginatedData;
}
/**
* Merge data from another JSON file into the current JSON file.
*
* @param string $path Path to the current JSON file
* @param string $otherFilePath Path to the other JSON file to merge from
*
* @throws Exception If there is an error decoding JSON or saving JSON content
*/
public static function mergeFromFile($path, $otherFilePath)
{
// Read the content of the current JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Read the content of the other JSON file
$otherFileContent = file_get_contents($otherFilePath);
// Decode the current JSON file content to an associative array
$currentData = json_decode($fileContent, true);
// Decode the other JSON file content to an associative array
$otherData = json_decode($otherFileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
// Merge data from other file
$mergedData = array_merge($currentData, $otherData);
// Encode the merged data back to JSON
$newJson = json_encode($mergedData, JSON_PRETTY_PRINT);
// Save the merged JSON back to the file
if (!file_put_contents($path, $newJson)) {
throw new Exception("Error saving merged JSON to file: {$path}");
}
}
/**
* Merge data from an array into the current JSON data.
*
* @param string $path Path to the JSON file
* @param array $dataArray Array of data to merge
*
* @throws Exception If there is an error decoding JSON or saving JSON content
*/
public static function mergeFromArray($path, array $dataArray)
{
// Read the content of the JSON file
$fileContent = file_exists($path) ? file_get_contents($path) : '{}'; // Default to an empty JSON object if the file doesn't exist
// Decode the current JSON file content to an associative array
$currentData = json_decode($fileContent, true);
// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error decoding JSON: " . json_last_error_msg());
}
// Merge the arrays
$mergedData = array_merge($currentData, $dataArray);
// Encode the merged data back to JSON
$newJson = json_encode($mergedData, JSON_PRETTY_PRINT);
// Save the merged JSON back to the file
if (!file_put_contents($path, $newJson)) {
throw new Exception("Error saving merged JSON to file: {$path}");
}
}
/**
* Backup the current JSON file to a specified location.
*
* @param string $path Path to the JSON file
* @param string $backupPath Path to save the backup file
*
* @throws Exception If there is an error copying the file
*/
public static function backup($path, $backupPath)
{
if (!copy($path, $backupPath)) {
throw new Exception("Error creating backup of the JSON file.");
}
}
/**
* Restore the JSON file from a specified backup location.
*
* @param string $path Path to the JSON file
* @param string $backupPath Path to the backup file
*
* @throws Exception If there is an error copying the file
*/
public static function restore($path, $backupPath)
{
if (!copy($backupPath, $path)) {
throw new Exception("Error restoring the JSON file from backup.");
}
}
}