Skip to content

Commit

Permalink
Added ontime validator picks
Browse files Browse the repository at this point in the history
  • Loading branch information
waxim committed Jan 18, 2017
1 parent 4085913 commit 658765b
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/Vouchers/Bag.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,34 @@ public function fill($number = 0)
*
* @return Voucher $voucher
*/
public function pick()
public function pick(callable $callback = null)
{
if ($callback) {
return $this->pickWithCallback($callback);
}

return $this->values[array_rand($this->values)];
}

/**
* Receive a callback and use it to pick
* a voucher.
*
* @param callable $callback
* @throws NoValidVouchers
* @return Voucher $voucher
*/
public function pickWithCallback(callable $callback)
{
foreach ($this->values as $voucher) {
if ($callback($voucher)) {
return $voucher;
}
}

throw new \Vouchers\Exceptions\NoValidVouchers();
}

/**
* Add an array to our collection.
*
Expand Down
40 changes: 40 additions & 0 deletions tests/Vouchers/BagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,44 @@ public function testFindAVoucher()
$test = $bag->find("MY-VOUCHER");
$this->assertSame($voucher, $test);
}

/**
* Test pick with callback.
*/
public function testPickWithACallback()
{
$bag = new \Vouchers\Bag();
$voucher = new \Vouchers\Voucher([
'code' => 'MY-Test-code',
'owner' => 'tester'
]);
$bag->add($voucher);

$test = $bag->pick(function ($voucher) {
return $voucher->get('owner') == "tester";
});

$this->assertSame($test, $voucher);
}

/**
* Test pick with callback.
*
* @expectedException \Vouchers\Exceptions\NoValidVouchers
*/
public function testPickWithACallbackFails()
{
$bag = new \Vouchers\Bag();
$voucher = new \Vouchers\Voucher([
'code' => 'MY-Test-code',
'owner' => 'tester'
]);
$bag->add($voucher);

$test = $bag->pick(function ($voucher) {
return $voucher->get('owner') == "not a tester";
});

$this->assertSame($test, $voucher);
}
}

0 comments on commit 658765b

Please sign in to comment.