MagentoPrimaryKey.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services\Asteria;
  3. use Illuminate\Support\Facades\DB;
  4. /**
  5. * Empty-catalog Asteria migration writes Magento entity_id / review_id as Bagisto PK.
  6. */
  7. class MagentoPrimaryKey
  8. {
  9. /**
  10. * @param array<int|string> $ids
  11. * @return array<int, int> occupied id => id
  12. */
  13. public static function occupiedIds(string $table, array $ids): array
  14. {
  15. $ids = array_values(array_unique(array_filter(
  16. array_map('intval', $ids),
  17. fn (int $id) => $id > 0
  18. )));
  19. if ($ids === []) {
  20. return [];
  21. }
  22. return DB::table($table)
  23. ->whereIn('id', $ids)
  24. ->pluck('id')
  25. ->map(fn ($id) => (int) $id)
  26. ->flip()
  27. ->all();
  28. }
  29. public static function bumpAutoIncrement(string $table): void
  30. {
  31. $driver = DB::connection()->getDriverName();
  32. if (! in_array($driver, ['mysql', 'mariadb'], true)) {
  33. return;
  34. }
  35. // DDL implicit-commits MySQL, which would leak rows from PHPUnit DatabaseTransactions.
  36. if (DB::connection()->transactionLevel() > 0) {
  37. return;
  38. }
  39. $max = (int) DB::table($table)->max('id');
  40. $next = max(1, $max + 1);
  41. $prefix = DB::connection()->getTablePrefix();
  42. $safe = str_replace(['`', '.', ' '], '', $table);
  43. DB::statement('ALTER TABLE `'.$prefix.$safe.'` AUTO_INCREMENT = '.$next);
  44. }
  45. }