Skip to content

Commit

Permalink
add except to random methods
Browse files Browse the repository at this point in the history
  • Loading branch information
miladrahimi committed Aug 4, 2021
1 parent 7f5fe89 commit 6a3cdaa
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,36 @@ public static function randomKey()
return array_rand(static::all());
}

/**
* Get a random key except given values
*
* @param array $values
* @return array|int|string
*/
public static function randomKeyExceptValues(array $values = [])
{
do {
$key = array_rand(static::all());
} while (in_array(static::all()[$key], $values));

return $key;
}

/**
* Get a random key except given keys
*
* @param array $keys
* @return array|int|string
*/
public static function randomKeyExceptKeys(array $keys = [])
{
do {
$key = array_rand(static::all());
} while (in_array($key, $keys));

return $key;
}

/**
* Get a random value
*
Expand All @@ -134,4 +164,34 @@ public static function randomValue()
{
return static::all()[array_rand(static::all())];
}

/**
* Get a random value except given values
*
* @param array $values
* @return mixed
*/
public static function randomValueExceptValues(array $values = [])
{
do {
$value = static::all()[array_rand(static::all())];
} while (in_array($value, $values));

return $value;
}

/**
* Get a random value except given keys
*
* @param array $keys
* @return mixed
*/
public static function randomValueExceptKeys(array $keys = [])
{
do {
$key = array_rand(static::all());
} while (in_array($key, $keys));

return static::all()[$key];
}
}
22 changes: 22 additions & 0 deletions tests/GeneralTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,30 @@ public function test_random_key()
$this->assertArrayHasKey(SampleEnum::randomKey(), SampleEnum::all());
}

public function test_random_key_except_keys()
{
$this->assertContains(SampleEnum::randomKeyExceptKeys(['ONE', 'TWO']), ['UNO', 'STR']);
}

public function test_random_key_except_values()
{
$this->assertContains(SampleEnum::randomKeyExceptValues([SampleEnum::STR, SampleEnum::TWO]), ['ONE', 'UNO']);
}

public function test_random_value()
{
$this->assertContains(SampleEnum::randomValue(), SampleEnum::all());
}

public function test_random_value_except_values()
{
$this->assertContains(SampleEnum::randomValueExceptValues([SampleEnum::STR, SampleEnum::TWO]),
[SampleEnum::ONE]
);
}

public function test_random_value_except_keys()
{
$this->assertContains(SampleEnum::randomValueExceptKeys(['STR', 'TWO']), [SampleEnum::ONE]);
}
}

0 comments on commit 6a3cdaa

Please sign in to comment.