Magento1Schema.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Services\Asteria;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Schema;
  5. /**
  6. * Schema helpers that work against Magento 1's MySQL 5.6.
  7. *
  8. * Laravel's Schema::hasColumn() reads information_schema.columns.generation_expression,
  9. * which does not exist until MySQL 5.7.
  10. */
  11. class Magento1Schema
  12. {
  13. /** @var array<string, array<int, string>> */
  14. private array $columns = [];
  15. /** @var array<string, bool> */
  16. private array $tables = [];
  17. public function __construct(private string $connection = 'asteria') {}
  18. public function hasTable(string $table): bool
  19. {
  20. return $this->tables[$table] ??= Schema::connection($this->connection)->hasTable($table);
  21. }
  22. /**
  23. * @param array<int, string> $candidates
  24. * @return array<int, string>
  25. */
  26. public function existingColumns(string $table, array $candidates): array
  27. {
  28. if (! $this->hasTable($table)) {
  29. return [];
  30. }
  31. $listing = array_fill_keys(array_map('strtolower', $this->columnListing($table)), true);
  32. return array_values(array_filter(
  33. $candidates,
  34. fn (string $column) => isset($listing[strtolower($column)])
  35. ));
  36. }
  37. /**
  38. * @return array<int, string>
  39. */
  40. public function columnListing(string $table): array
  41. {
  42. if (isset($this->columns[$table])) {
  43. return $this->columns[$table];
  44. }
  45. $connection = DB::connection($this->connection);
  46. if ($connection->getDriverName() === 'mysql') {
  47. $wrapped = $connection->getQueryGrammar()->wrapTable($table);
  48. $rows = $connection->select('show columns from '.$wrapped);
  49. $names = [];
  50. foreach ($rows as $row) {
  51. $row = (array) $row;
  52. $name = $row['Field'] ?? $row['field'] ?? null;
  53. if (is_string($name) && $name !== '') {
  54. $names[] = $name;
  55. }
  56. }
  57. return $this->columns[$table] = $names;
  58. }
  59. return $this->columns[$table] = Schema::connection($this->connection)->getColumnListing($table);
  60. }
  61. }