Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created May 20, 2022 08:40
Show Gist options
  • Save yowcow/63fde73ebf76d4f316fcc1e44d3e649e to your computer and use it in GitHub Desktop.
Save yowcow/63fde73ebf76d4f316fcc1e44d3e649e to your computer and use it in GitHub Desktop.
<?php
interface RandomGeneratorInterface
{
public function getString(int $length): string;
public function getBytes(int $length): string;
}
class RandomFileReader implements RandomGeneratorInterface
{
public function __construct(
private $fh = null,
string $path = '/dev/urandom',
) {
if (!$this->fh) {
$this->fh = fopen($path, 'r');
}
}
public function getString(int $length): string
{
return bin2hex($this->getBytes($length));
}
public function getBytes(int $length): string
{
return fread($this->fh, $length);
}
}
$rand = new RandomFileReader();
echo "random-hex: {$rand->getString(4)}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment