CourseCriteria.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Repositories\Criteria\Course;
  3. use App\Repositories\Enums\ModelStatusEnum;
  4. use Carbon\Carbon;
  5. use Illuminate\Http\Request;
  6. use Prettus\Repository\Contracts\CriteriaInterface;
  7. use Prettus\Repository\Contracts\RepositoryInterface;
  8. /**
  9. * Class CourseCriteria.
  10. *
  11. * @package namespace App\Repositories\Criteria;
  12. */
  13. class CourseCriteria implements CriteriaInterface
  14. {
  15. /**
  16. * Apply criteria in query repository
  17. *
  18. * @param string $model
  19. * @param RepositoryInterface $repository
  20. *
  21. * @return mixed
  22. */
  23. public function __construct(Request $request = null)
  24. {
  25. if (is_null($request)) {
  26. $this->request = \request();
  27. } else {
  28. $this->request = $request;
  29. }
  30. }
  31. /**
  32. * Apply criteria in query repository
  33. *
  34. * @param string $model
  35. * @param RepositoryInterface $repository
  36. *
  37. * @return mixed
  38. */
  39. public function apply($model, RepositoryInterface $repository)
  40. {
  41. if ($this->request->filled('title')) {
  42. $title = $this->request->get('title');
  43. $model = $model->where('title', 'like', "%{$title}%");
  44. }
  45. if ($this->request->filled('status')) {
  46. $status = $this->request->get('status', 0);
  47. $model = $model->where('status', '=', $status);
  48. }
  49. if ($this->request->filled('category_id')) {
  50. $category_id = $this->request->get('category_id', 0);
  51. $model = $model->where('category_id', '=', $category_id);
  52. }
  53. if ($this->request->filled('tag')) {
  54. $tag = $this->request->get('tag');
  55. switch ($tag) {
  56. case 'new':
  57. $model = $model->orderByDesc('id');
  58. break;
  59. case 'hot':
  60. $model = $model->orderByDesc('user_count')->orderByDesc('id');
  61. break;
  62. case 'rec':
  63. $model = $model->orderByDesc('is_rec')->orderByDesc('id');
  64. break;
  65. }
  66. } else {
  67. if (!$this->request->filled('orderBy')) {
  68. $model = $model->orderByDesc('sort')->orderByDesc('id');
  69. }
  70. }
  71. if (isApi()) {
  72. $model = $model->where('status', ModelStatusEnum::OK)->where('published_at', '<=', Carbon::now()->toDateTimeString());
  73. }
  74. return $model;
  75. }
  76. }