BaseRepository.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Repositories\Eloquent;
  11. use App\Repositories\Presenters\Presenter;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Prettus\Repository\Eloquent\BaseRepository as BaseRepositoryEloquent;
  14. abstract class BaseRepository extends BaseRepositoryEloquent
  15. {
  16. /**
  17. * @var Presenter
  18. */
  19. protected $presenter;
  20. /**
  21. * Retrieve all data of repository, simple paginated.
  22. *
  23. * @param null|int $limit
  24. * @param array $columns
  25. *
  26. * @return mixed
  27. */
  28. public function cursorPaginate($limit = null, $columns = ['*'])
  29. {
  30. return $this->paginate($limit, $columns, 'cursor');
  31. }
  32. /**
  33. * Retrieve all data of repository, paginated.
  34. *
  35. * @param null|int $limit
  36. * @param array $columns
  37. * @param string $method
  38. *
  39. * @return mixed
  40. */
  41. public function paginate($limit = null, $columns = ['*'], $method = 'paginate')
  42. {
  43. $this->applyCriteria();
  44. $this->applyScope();
  45. $limit = is_null($limit) ? config('repository.pagination.limit', 15) : (int) $limit;
  46. if ($method === 'cursor') {
  47. $results = $this->model->select($columns)->limit($limit)->get();
  48. if ($this->model instanceof Builder) {
  49. $primaryKey = $this->model->getModel()->getKeyName();
  50. } else {
  51. $primaryKey = $this->model->getKeyName();
  52. }
  53. $count = $results->count();
  54. $next = $count === $limit ? optional($results->last())->{$primaryKey} : null;
  55. $prev = request('prev');
  56. $this->presenter->makeCursor((int) request('cursor'), $prev ? (int) $prev : null, $next, $count);
  57. } else {
  58. $results = $this->model->{$method}($limit, $columns);
  59. $results->appends(app('request')->query());
  60. }
  61. $this->resetModel();
  62. return $this->parserResult($results);
  63. }
  64. }