Skip to content

Commit b694b9b

Browse files
committed
add class Random
1 parent d50b485 commit b694b9b

File tree

3 files changed

+45
-15
lines changed

3 files changed

+45
-15
lines changed

src/Random.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Utilitte\Php;
4+
5+
use InvalidArgumentException;
6+
7+
final class Random
8+
{
9+
10+
public static function chance(int $percentage, bool $strict = true): bool
11+
{
12+
if ($percentage <= 0) {
13+
if ($strict && $percentage < 0) {
14+
throw new InvalidArgumentException('Percentage must be greater than or equal to 0');
15+
}
16+
17+
return false;
18+
} elseif ($percentage >= 100) {
19+
if ($strict && $percentage > 100) {
20+
throw new InvalidArgumentException('Percentage must be less than or equal to 100');
21+
}
22+
23+
return true;
24+
}
25+
26+
return mt_rand(1, 100) <= $percentage;
27+
}
28+
29+
}

tests/cases/arrays.columnAsKey.phpt

Lines changed: 0 additions & 15 deletions
This file was deleted.

tests/cases/random.chance.phpt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php declare(strict_types = 1);
2+
3+
// phpcs:ignoreFile
4+
5+
use Tester\Assert;
6+
use Utilitte\Php\Random;
7+
8+
require __DIR__ . '/../bootstrap.php';
9+
10+
Assert::true(Random::chance(100));
11+
Assert::true(Random::chance(101, false));
12+
Assert::false(Random::chance(0));
13+
Assert::false(Random::chance(-1, false));
14+
15+
Assert::exception(fn () => Random::chance(-1), InvalidArgumentException::class);
16+
Assert::exception(fn () => Random::chance(101), InvalidArgumentException::class);

0 commit comments

Comments
 (0)