Last active
July 17, 2024 19:12
-
-
Save edgrosvenor/58b54bc4213a3ba192c3f7b340286f1f to your computer and use it in GitHub Desktop.
Kind of like the Laravel Lottery helper, but with unlimited outcomes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'](); | |
} | |
} |
Author
edgrosvenor
commented
Jul 17, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment