PagingTrait.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Http\Traits;
  3. use Illuminate\Pagination\Paginator;
  4. use Illuminate\Pagination\LengthAwarePaginator;
  5. use stdClass;
  6. trait PagingTrait
  7. {
  8. public function getPageOffset(int $page = 1, int $perPage = DEFAULT_LIST_PER_PAGE): int
  9. {
  10. return ($page > 0 ? (($page - 1) * $perPage) : 1);
  11. }
  12. public function getPaginator(array $items, int $total, int $perPage, int|null $page, string $path = null, string $query = null): LengthAwarePaginator
  13. {
  14. $request = Request();
  15. $allowed = ['search', 'keyword', 'category', 'sort', 'order', 'perPage'];
  16. $query = $request->only($allowed);
  17. return new LengthAwarePaginator($items, $total, $perPage, $page, [
  18. 'path' => ($path ?? $request->url()),
  19. 'query' => ($query ?? $request->query())
  20. ]);
  21. }
  22. /**
  23. * generate a hierarchical structure of comments for loop
  24. * @param object $list
  25. * @param int $total
  26. */
  27. public function generateList(object $list, int $total = 0)
  28. {
  29. $root = new stdClass;
  30. for ($i = $total - 1; $i >= 0; $i--) {
  31. $key = $list[$i]->key;
  32. $parent = $list[$i]->parent;
  33. if (!$key) {
  34. continue;
  35. }
  36. $list[$key] = $list[$i];
  37. if ($parent) {
  38. $list[$parent]->child[] = &$list[$key];
  39. } else {
  40. $root->child[] = &$list[$key];
  41. }
  42. }
  43. $this->relocateList($list, $root->child, 0, null);
  44. }
  45. /**
  46. * Relocate comments in the hierarchical structure
  47. * @param $pList
  48. * @param array $cList
  49. * @param $depth
  50. * @param null $parent
  51. */
  52. private function relocateList(&$pList, array $cList, $depth, $parent = null)
  53. {
  54. if (!is_array($cList) || !count($cList)) {
  55. return;
  56. }
  57. foreach ($cList as $key => $val) {
  58. if ($parent) {
  59. $val->head = $parent->head;
  60. } else {
  61. $val->head = $val->comment_srl;
  62. }
  63. $val->arrange = count($pList) + 1;
  64. if ($val->child) {
  65. $val->depth = $depth;
  66. $pList[$val->comment_srl] = $val;
  67. $this->relocateList($pList, $val->child, $depth + 1, $val);
  68. unset($val->child);
  69. } else {
  70. $val->depth = $depth;
  71. $pList[$val->comment_srl] = $val;
  72. }
  73. }
  74. }
  75. }