PagingTrait.php 2.4 KB

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