Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- final class Loop
- {
- /**
- * @var object
- */
- private $counter;
- /**
- * @var bool
- */
- private $first;
- public function __construct()
- {
- $this->reset();
- }
- public function reset()
- {
- $this->counter = $this->getCounter();
- $this->first = true;
- }
- public function onFirst(callable $callable, ...$args)
- {
- $return = $this->incrementAndReturn($this->first, $callable, ...$args);
- $this->first = false;
- return $return;
- }
- public function onNth(int $n, callable $callable, ...$args)
- {
- return $this->incrementAndReturn($this->counter->count() === $n, $callable, ...$args);
- }
- public function onOdd(callable $callable, ...$args)
- {
- return $this->incrementAndReturn($this->counter->mod(2) !== 0, $callable, ...$args);
- }
- public function onEven(callable $callable, ...$args)
- {
- return $this->incrementAndReturn($this->counter->mod(2) === 0, $callable, ...$args);
- }
- private function incrementAndReturn(bool $condition, callable $callable, ...$args)
- {
- try {
- if ($condition) {
- return ($callable)(...$args);
- }
- } finally {
- $this->counter->inc();
- }
- }
- private static function getCounter()
- {
- return new class
- {
- private $count = 1;
- public function inc()
- {
- $this->count++;
- }
- public function mod($i)
- {
- return $this->count % $i;
- }
- public function count()
- {
- return $this->count;
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement