領収証発行サービス
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1KB

  1. <?php
  2. namespace App\Util;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Facades\DB;
  5. class SelectQueryUtil
  6. {
  7. public static function select(array|string $columns, string $as = null): static
  8. {
  9. return new static($columns, $as);
  10. }
  11. public static function value(string|int $val, string $as)
  12. {
  13. if (is_string($val)) {
  14. return DB::raw(sprintf("'%s' as %s", $val, $as));
  15. } else if (is_int($val)) {
  16. return DB::raw(sprintf("CAST('%s' as INTEGER) as %s", $val, $as));
  17. }
  18. return "";
  19. }
  20. private string $columnName;
  21. private string|null $as = null;
  22. private string|int|null $nullValue = null;
  23. public function __construct(array|string $column, string $as = null)
  24. {
  25. if (is_string($column)) {
  26. $this->columnName = $column;
  27. $this->as = $column;
  28. } else {
  29. $ret = "";
  30. foreach ($column as $c) {
  31. if ($ret !== "") {
  32. $ret .= ".";
  33. }
  34. $ret .= sprintf('"%s"', $c);
  35. }
  36. $this->columnName = $ret;
  37. $this->as = Arr::last($column);
  38. }
  39. if ($as !== null) {
  40. $this->as = $as;
  41. }
  42. }
  43. public function as(string $as): static
  44. {
  45. $this->as = $as;
  46. return $this;
  47. }
  48. public function nullValue(string|int|null $nullValue): static
  49. {
  50. $this->nullValue = $nullValue;
  51. return $this;
  52. }
  53. public function build()
  54. {
  55. $query = $this->columnName;
  56. $needRaw = true;
  57. if ($this->nullValue !== null) {
  58. if (is_string($this->nullValue)) {
  59. $query = sprintf("COALESCE(%s, '%s')", $query, $this->nullValue);
  60. $needRaw = true;
  61. } else if (is_int($this->nullValue)) {
  62. $query = sprintf("COALESCE(%s, %d)", $query, $this->nullValue);
  63. $needRaw = true;
  64. }
  65. }
  66. if ($this->as !== null) {
  67. $query = sprintf('%s as %s', $query, $this->as);
  68. }
  69. return $needRaw ? DB::raw($query) : $query;
  70. }
  71. }