1. <?php
  2. /**
  3. * CLI tool for restoring user data. FOR DEVELOPMENT USE ONLY.
  4. */
  5. require_once 'vendor/autoload.php'; // Assuming you're using Composer
  6. use Firebase\Firestore\Firestore;
  7. // Configuration - Replace with your actual values
  8. define('FIRESTORE_COLLECTION', 'users'); // Collection name
  9. define('RESTORE_FILE', 'restore_data.json'); // File containing the data to restore
  10. /**
  11. * Restores user data from a JSON file to Firestore.
  12. *
  13. * @param string $restoreFilePath Path to the JSON file containing the data.
  14. * @return bool True on success, false on failure.
  15. */
  16. function restoreData(string $restoreFilePath): bool
  17. {
  18. try {
  19. // Load data from the JSON file
  20. $data = json_decode(file_get_contents($restoreFilePath), true);
  21. if ($data === null) {
  22. error_log("Error: Failed to decode JSON from " . $restoreFilePath);
  23. return false;
  24. }
  25. // Initialize Firestore
  26. $db = Firestore::create();
  27. // Iterate through the data and insert each user
  28. foreach ($data as $user) {
  29. $db->collection(FIRESTORE_COLLECTION)->add($user);
  30. }
  31. error_log("Data restored successfully from " . $restoreFilePath . " to Firestore.");
  32. return true;
  33. } catch (\Exception $e) {
  34. error_log("Error restoring data: " . $e->getMessage());
  35. return false;
  36. }
  37. }
  38. // Check if the restore file is provided as a command-line argument
  39. if (isset($argv[1])) {
  40. $restoreFilePath = $argv[1];
  41. if (restoreData($restoreFilePath)) {
  42. echo "Data restoration completed.\n";
  43. } else {
  44. echo "Data restoration failed.\n";
  45. }
  46. } else {
  47. echo "Usage: php restore.php <path_to_restore_file.json>\n";
  48. }
  49. ?>

Add your comment