領収証発行サービス
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.

82 lines
2.2KB

  1. <?php
  2. namespace App\Repositories;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Support\Arr;
  5. abstract class BaseRepository
  6. {
  7. const ORDER_ASC = "asc";
  8. const ORDER_DESC = "desc";
  9. const CONDITION_SORT_TARGET = "sort";
  10. const CONDITION_SORT_ORDER = "order";
  11. const CONDITION_LIMIT = "limit";
  12. const MAX_LIMIT = 500;
  13. protected function sort(Builder $query, array $condition)
  14. {
  15. $target = data_get($condition, self::CONDITION_SORT_TARGET);
  16. $order = data_get($condition, self::CONDITION_SORT_ORDER);
  17. if ($target === null || $order === null) {
  18. return;
  19. }
  20. if ($order === static::ORDER_ASC) {
  21. $query->orderBy($target);
  22. }
  23. if ($order === static::ORDER_DESC) {
  24. $query->orderByDesc($target);
  25. }
  26. }
  27. protected function limit(Builder $query, array $condition, ?int $default = null)
  28. {
  29. $limit = data_get($condition, self::CONDITION_LIMIT, $default) ?? $default ?? static::MAX_LIMIT;
  30. $limit = min($limit, self::MAX_LIMIT);
  31. $query->limit($limit);
  32. }
  33. protected function where(Builder $query, array $condition, string $conditionKey, string|null $columnName = null): bool
  34. {
  35. $ret = data_get($condition, $conditionKey);
  36. if ($ret !== null) {
  37. $query->where($columnName ?? $conditionKey, $ret);
  38. return true;
  39. } else {
  40. return false;
  41. }
  42. }
  43. protected function whereIn(Builder $query, array $condition, string $conditionKey, string|null $columnName = null): bool
  44. {
  45. $ret = data_get($condition, $conditionKey);
  46. if ($ret !== null && is_array($ret)) {
  47. $query->whereIn($columnName ?? $conditionKey, $ret);
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. protected function makeColumnName(array $targets, ?string $as = null): string
  54. {
  55. $as = $as ? " as {$as}" : "";
  56. return implode('.', $targets) . $as;
  57. }
  58. protected function makeColumnNameForSelect(array $targets, ?string $as = null): string
  59. {
  60. $as = $as ? " as {$as}" : " as " . Arr::last($targets);
  61. return implode('.', $targets) . $as;
  62. }
  63. }