ManagesLoops.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Illuminate\View\Concerns;
  3. use Countable;
  4. use Illuminate\Support\Arr;
  5. trait ManagesLoops
  6. {
  7. /**
  8. * The stack of in-progress loops.
  9. *
  10. * @var array
  11. */
  12. protected $loopsStack = [];
  13. /**
  14. * Add new loop to the stack.
  15. *
  16. * @param \Countable|array $data
  17. * @return void
  18. */
  19. public function addLoop($data)
  20. {
  21. $length = is_array($data) || $data instanceof Countable ? count($data) : null;
  22. $parent = Arr::last($this->loopsStack);
  23. $this->loopsStack[] = [
  24. 'iteration' => 0,
  25. 'index' => 0,
  26. 'remaining' => $length ?? null,
  27. 'count' => $length,
  28. 'first' => true,
  29. 'last' => isset($length) ? $length == 1 : null,
  30. 'depth' => count($this->loopsStack) + 1,
  31. 'parent' => $parent ? (object) $parent : null,
  32. ];
  33. }
  34. /**
  35. * Increment the top loop's indices.
  36. *
  37. * @return void
  38. */
  39. public function incrementLoopIndices()
  40. {
  41. $loop = $this->loopsStack[$index = count($this->loopsStack) - 1];
  42. $this->loopsStack[$index] = array_merge($this->loopsStack[$index], [
  43. 'iteration' => $loop['iteration'] + 1,
  44. 'index' => $loop['iteration'],
  45. 'first' => $loop['iteration'] == 0,
  46. 'remaining' => isset($loop['count']) ? $loop['remaining'] - 1 : null,
  47. 'last' => isset($loop['count']) ? $loop['iteration'] == $loop['count'] - 1 : null,
  48. ]);
  49. }
  50. /**
  51. * Pop a loop from the top of the loop stack.
  52. *
  53. * @return void
  54. */
  55. public function popLoop()
  56. {
  57. array_pop($this->loopsStack);
  58. }
  59. /**
  60. * Get an instance of the last loop in the stack.
  61. *
  62. * @return \stdClass|null
  63. */
  64. public function getLastLoop()
  65. {
  66. if ($last = Arr::last($this->loopsStack)) {
  67. return (object) $last;
  68. }
  69. }
  70. /**
  71. * Get the entire loop stack.
  72. *
  73. * @return array
  74. */
  75. public function getLoopStack()
  76. {
  77. return $this->loopsStack;
  78. }
  79. }