-
Notifications
You must be signed in to change notification settings - Fork 0
/
ManageRandomItemsTrait.php
67 lines (60 loc) · 1.35 KB
/
ManageRandomItemsTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace GregorJ\CorrectHorse\Generators;
use function array_rand;
use function shuffle;
/**
* Trait ManageRandomItemsTrait
* Manage common tasks with random items.
*/
trait ManageRandomItemsTrait
{
/**
* @var array
*/
private $items = [];
/**
* Clear all generated items.
* @return void
*/
public function reset(): void
{
$this->items = [];
}
/**
* Remove a random generated item.
* @return void
*/
public function remove(): void
{
if ($this->has()) {
unset($this->items[array_rand($this->items)]);
}
}
/**
* Are there any randomly generated items?
* @return bool
*/
public function has(): bool
{
return $this->items !== [];
}
/**
* Get all randomly generated items in random order.
* @return array
*/
public function get(): array
{
// in case there are no random items, return an empty array
if (!$this->has()) {
return [];
}
// in case there is just one item, there is no need to shuffle
if (count($this->items) === 1) {
return $this->items;
}
// get the generated items in random order before returning them
$items = $this->items;
shuffle($items);
return $items;
}
}