Skip to content

Commit

Permalink
Extended Loop with multiple every n-th.
Browse files Browse the repository at this point in the history
  • Loading branch information
bbankowski committed Jan 24, 2022
1 parent 04825af commit 61cbe8c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 23 deletions.
32 changes: 17 additions & 15 deletions Utilities/Loop/Loop.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,20 @@

class Loop
{
private int $iterations;
private int $delay;
private ?Closure $functionForEach;
private ?Closure $functionForEveryNth;
private ?int $n;

private int $currentIteration = 0;

public function __construct(int $iterations, int $delay, ?Closure $functionForEach, ?Closure $functionForEveryNth, ?int $n)
/**
* @param Closure[] $functionForEveryNth
* @param int[] $n
*/
public function __construct(
private int $iterations,
private int $delay,
private ?Closure $functionForEach,
private array $functionForEveryNth,
private array $n,
)
{
$this->iterations = $iterations;
$this->delay = $delay;
$this->functionForEach = $functionForEach;
$this->functionForEveryNth = $functionForEveryNth;
$this->n = $n;
}

public static function of(int $iterations): LoopBuilder
Expand All @@ -45,9 +44,12 @@ public function run(): void
$function($this->currentIteration);
}

if (is_callable($this->functionForEveryNth) && $this->n > 0 && ($this->currentIteration % $this->n === 0)) {
$function = $this->functionForEveryNth;
$function($this->currentIteration);
for ($i = 0; $i < sizeof($this->functionForEveryNth); $i++) {
$function = $this->functionForEveryNth[$i];
$n = $this->n[$i];
if (is_callable($function) && $n > 0 && ($this->currentIteration % $n === 0)) {
$function($this->currentIteration);
}
}

sleep($this->delay);
Expand Down
15 changes: 7 additions & 8 deletions Utilities/Loop/LoopBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@

class LoopBuilder
{
private int $iterations;

private int $delay = 1;
private ?Closure $functionForEach = null;
private ?Closure $functionForEveryNth = null;
private ?int $n = null;
/** @var Closure[] */
private array $functionForEveryNth = [];
/** @var int[] */
private array $n = [];

public function __construct(int $iterations)
public function __construct(private int $iterations)
{
$this->iterations = $iterations;
}

public function withFixedDelay(int $seconds): LoopBuilder
Expand All @@ -36,8 +35,8 @@ public function forEach(Closure $function): LoopBuilder

public function forEveryNth(int $n, Closure $function): LoopBuilder
{
$this->functionForEveryNth = $function;
$this->n = $n;
$this->functionForEveryNth[] = $function;
$this->n[] = $n;
return $this;
}

Expand Down

0 comments on commit 61cbe8c

Please sign in to comment.