Skip to content

Instantly share code, notes, and snippets.

@edgrosvenor
Last active July 17, 2024 19:12
Show Gist options
  • Save edgrosvenor/58b54bc4213a3ba192c3f7b340286f1f to your computer and use it in GitHub Desktop.
Save edgrosvenor/58b54bc4213a3ba192c3f7b340286f1f to your computer and use it in GitHub Desktop.
Kind of like the Laravel Lottery helper, but with unlimited outcomes
<?php
use Illuminate\Support\Collection;
class Raffle
{
private int $total = 0;
private int $current = 0;
private Collection $entries;
public function __construct()
{
$this->entries = collect();
}
public static function make(): Raffle
{
return new self();
}
public function add(int $tickets, callable $callback): static
{
$this->entries->push([
'win' => range($this->current + 1, $this->current + $tickets),
'callback' => $callback,
]);
$this->current += $tickets;
$this->total += $tickets;
return $this;
}
public function run()
{
$selected = $this->entries->pluck('win')->flatten()->random(1)->first();
$winner = $this->entries->filter(fn($entry) => in_array($selected, $entry['win'], true))->first();
return $winner['callback']();
}
}
@edgrosvenor
Copy link
Author

Raffle::make()
  ->add(10, fn() => "this")
  ->add(10, fn() => "that")
  ->add(20, fn() => "the other thing")
  ->run();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment