Skip to content

Commit

Permalink
Add onceIf method (#35)
Browse files Browse the repository at this point in the history
* test

* add onceif

* readme
  • Loading branch information
jasonvarga committed Jun 30, 2023
1 parent db77af6 commit bdbe28e
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,24 @@ public function has(string $name) : bool
*
* @return mixed
*/
public function once($key, callable $callable)
```

### onceIf

```php
/**
* Use the "once" method only if the given condition is true.
*
* Otherwise, the callable will be executed.
*
* @param bool $shouldBlink
* @param $key
* @param callable
*
* @return mixed
*/
public function onceIf($shouldBlink, $key, callable $callable)
```

### all
Expand Down
12 changes: 12 additions & 0 deletions src/Blink.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,18 @@ public function once($key, callable $callable)
return $this->get($key);
}

/**
* Use the "once" method only if the given condition is true.
*
* Otherwise, the callable will be executed.
*
* @return mixed
*/
public function onceIf($shouldBlink, $key, callable $callable)
{
return $shouldBlink ? $this->once($key, $callable) : $callable();
}

protected function filterKeysStartingWith(array $values, string $startsWith): array
{
return array_filter($values, function ($key) use ($startsWith) {
Expand Down
18 changes: 18 additions & 0 deletions tests/BlinkTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -481,4 +481,22 @@ public function it_can_perform_a_function_only_once()
$this->assertSame($firstResult, $this->blink->once('random', $callable));
}
}

/** @test */
public function it_can_perform_a_function_only_once_conditionally()
{
$count = 0;
$callable = function () use (&$count) {
$count++;

return $count;
};

$this->assertSame(1, $this->blink->onceIf(false, 'key', $callable));
$this->assertSame(2, $this->blink->onceIf(true, 'key', $callable));
$this->assertSame(2, $this->blink->onceIf(true, 'key', $callable));
$this->assertSame(3, $this->blink->onceIf(false, 'key', $callable));
$this->assertSame(4, $this->blink->onceIf(false, 'key', $callable));
$this->assertSame(2, $this->blink->onceIf(true, 'key', $callable));
}
}

0 comments on commit bdbe28e

Please sign in to comment.