Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. final class Loop
  2. {
  3. /**
  4. * @var object
  5. */
  6. private $counter;
  7.  
  8. /**
  9. * @var bool
  10. */
  11. private $first;
  12.  
  13. public function __construct()
  14. {
  15. $this->reset();
  16. }
  17.  
  18. public function reset()
  19. {
  20. $this->counter = $this->getCounter();
  21. $this->first = true;
  22. }
  23.  
  24. public function onFirst(callable $callable, ...$args)
  25. {
  26. $return = $this->incrementAndReturn($this->first, $callable, ...$args);
  27. $this->first = false;
  28. return $return;
  29. }
  30.  
  31. public function onNth(int $n, callable $callable, ...$args)
  32. {
  33. return $this->incrementAndReturn($this->counter->count() === $n, $callable, ...$args);
  34. }
  35.  
  36. public function onOdd(callable $callable, ...$args)
  37. {
  38. return $this->incrementAndReturn($this->counter->mod(2) !== 0, $callable, ...$args);
  39. }
  40.  
  41. public function onEven(callable $callable, ...$args)
  42. {
  43. return $this->incrementAndReturn($this->counter->mod(2) === 0, $callable, ...$args);
  44. }
  45.  
  46. private function incrementAndReturn(bool $condition, callable $callable, ...$args)
  47. {
  48. try {
  49. if ($condition) {
  50. return ($callable)(...$args);
  51. }
  52. } finally {
  53. $this->counter->inc();
  54. }
  55. }
  56.  
  57. private static function getCounter()
  58. {
  59. return new class
  60. {
  61. private $count = 1;
  62.  
  63. public function inc()
  64. {
  65. $this->count++;
  66. }
  67.  
  68. public function mod($i)
  69. {
  70. return $this->count % $i;
  71. }
  72.  
  73. public function count()
  74. {
  75. return $this->count;
  76. }
  77. };
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement