TableCollector.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\DbConnection\Collector;
  12. use Hyperf\Database\Schema\Column;
  13. use InvalidArgumentException;
  14. class TableCollector
  15. {
  16. /**
  17. * @var array<string, array<string, Column>>
  18. */
  19. protected array $data = [];
  20. /**
  21. * @param Column[] $columns
  22. */
  23. public function set(string $pool, string $table, array $columns): void
  24. {
  25. $this->validateColumns($columns);
  26. $this->data[$pool][$table] = $columns;
  27. }
  28. public function add(string $pool, Column $column): void
  29. {
  30. $this->data[$pool][$column->getTable()][$column->getName()] = $column;
  31. }
  32. public function get(string $pool, ?string $table = null): array
  33. {
  34. if ($table === null) {
  35. return $this->data[$pool] ?? [];
  36. }
  37. return $this->data[$pool][$table] ?? [];
  38. }
  39. public function has(string $pool, ?string $table = null): bool
  40. {
  41. return ! empty($this->get($pool, $table));
  42. }
  43. public function getDefaultValue(string $connectName, string $table): array
  44. {
  45. $columns = $this->get($connectName, $table);
  46. $list = [];
  47. foreach ($columns as $column) {
  48. $list[$column->getName()] = $column->getDefault();
  49. }
  50. return $list;
  51. }
  52. /**
  53. * @throws InvalidArgumentException When $columns is not equal to Column[]
  54. */
  55. protected function validateColumns(array $columns): void
  56. {
  57. foreach ($columns as $column) {
  58. if (! $column instanceof Column) {
  59. throw new InvalidArgumentException('Invalid columns.');
  60. }
  61. }
  62. }
  63. }