PagingTrait.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. return new LengthAwarePaginator($items, $total, $perPage, $page, [
  16. 'path' => ($path ?? $request->url()),
  17. 'query' => ($query ?? $request->query())
  18. ]);
  19. }
  20. /**
  21. * generate a hierarchical structure of comments for loop
  22. * @param object $list
  23. * @param int $total
  24. */
  25. public function generateList(object $list, int $total = 0)
  26. {
  27. $root = new stdClass;
  28. for ($i = $total - 1; $i >= 0; $i--) {
  29. $key = $list[$i]->key;
  30. $parent = $list[$i]->parent;
  31. if (!$key) {
  32. continue;
  33. }
  34. $list[$key] = $list[$i];
  35. if ($parent) {
  36. $list[$parent]->child[] = &$list[$key];
  37. } else {
  38. $root->child[] = &$list[$key];
  39. }
  40. }
  41. $this->relocateList($list, $root->child, 0, null);
  42. }
  43. /**
  44. * Relocate comments in the hierarchical structure
  45. * @param $pList
  46. * @param array $cList
  47. * @param $depth
  48. * @param null $parent
  49. */
  50. private function relocateList(&$pList, array $cList, $depth, $parent = null)
  51. {
  52. if (!is_array($cList) || !count($cList)) {
  53. return;
  54. }
  55. foreach ($cList as $key => $val) {
  56. if ($parent) {
  57. $val->head = $parent->head;
  58. } else {
  59. $val->head = $val->comment_srl;
  60. }
  61. $val->arrange = count($pList) + 1;
  62. if ($val->child) {
  63. $val->depth = $depth;
  64. $pList[$val->comment_srl] = $val;
  65. $this->relocateList($pList, $val->child, $depth + 1, $val);
  66. unset($val->child);
  67. } else {
  68. $val->depth = $depth;
  69. $pList[$val->comment_srl] = $val;
  70. }
  71. }
  72. }
  73. }