Magento1Schema.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. public function __construct(private string $connection = 'asteria') {}
  16. public function hasTable(string $table): bool
  17. {
  18. return Schema::connection($this->connection)->hasTable($table);
  19. }
  20. /**
  21. * @param array<int, string> $candidates
  22. * @return array<int, string>
  23. */
  24. public function existingColumns(string $table, array $candidates): array
  25. {
  26. if (! $this->hasTable($table)) {
  27. return [];
  28. }
  29. $listing = array_fill_keys(array_map('strtolower', $this->columnListing($table)), true);
  30. return array_values(array_filter(
  31. $candidates,
  32. fn (string $column) => isset($listing[strtolower($column)])
  33. ));
  34. }
  35. /**
  36. * @return array<int, string>
  37. */
  38. public function columnListing(string $table): array
  39. {
  40. if (isset($this->columns[$table])) {
  41. return $this->columns[$table];
  42. }
  43. $connection = DB::connection($this->connection);
  44. if ($connection->getDriverName() === 'mysql') {
  45. $wrapped = $connection->getQueryGrammar()->wrapTable($table);
  46. $rows = $connection->select('show columns from '.$wrapped);
  47. $names = [];
  48. foreach ($rows as $row) {
  49. $row = (array) $row;
  50. $name = $row['Field'] ?? $row['field'] ?? null;
  51. if (is_string($name) && $name !== '') {
  52. $names[] = $name;
  53. }
  54. }
  55. return $this->columns[$table] = $names;
  56. }
  57. return $this->columns[$table] = Schema::connection($this->connection)->getColumnListing($table);
  58. }
  59. }