LegacySettingsMigration.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Classes;
  3. use Exception;
  4. use Illuminate\Support\Facades\DB;
  5. use Spatie\LaravelSettings\Migrations\SettingsMigration;
  6. abstract class LegacySettingsMigration extends SettingsMigration
  7. {
  8. public function getNewValue(string $name, string $group)
  9. {
  10. $new_value = DB::table('settings')->where([['group', '=', $group], ['name', '=', $name]])->get(['payload'])->first();
  11. if (is_null($new_value) || is_null($new_value->payload)) {
  12. return null;
  13. }
  14. // Some keys returns '""' as a value.
  15. if ($new_value->payload === '""') {
  16. return null;
  17. }
  18. // remove the quotes from the string
  19. if (substr($new_value->payload, 0, 1) === '"' && substr($new_value->payload, -1) === '"') {
  20. return substr($new_value->payload, 1, -1);
  21. }
  22. return $new_value->payload;
  23. }
  24. /**
  25. * Get the old value from the settings_old table.
  26. * @param string $key The key to get the value from table.
  27. * @param int|string|bool|null $default The default value to return if the value is null. If value is not nullable, a default must be provided.
  28. */
  29. public function getOldValue(string $key, int|string|bool|null $default = null)
  30. {
  31. $old_value = DB::table('settings_old')->where('key', '=', $key)->get(['value', 'type'])->first();
  32. if (is_null($old_value) || is_null($old_value->value)) {
  33. return $default;
  34. }
  35. switch ($old_value->type) {
  36. case 'string':
  37. case 'text':
  38. // Edgecase: The value is a boolean, but it's stored as a string.
  39. if ($old_value->value === "false" || $old_value->value === "true") {
  40. return filter_var($old_value->value, FILTER_VALIDATE_BOOL);
  41. }
  42. return $old_value->value;
  43. case 'boolean':
  44. return filter_var($old_value->value, FILTER_VALIDATE_BOOL);
  45. case 'integer':
  46. return filter_var($old_value->value, FILTER_VALIDATE_INT);
  47. default:
  48. throw new Exception("Unknown type: {$old_value->type}");
  49. }
  50. }
  51. }