49 lines
1 KiB
PHP
49 lines
1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domain\Services;
|
|
|
|
use Domain\Models\ValueObjects\Code;
|
|
use Domain\Ports\Directories\CodeDirectory;
|
|
|
|
class CodeGenerationService
|
|
{
|
|
public function __construct(
|
|
private readonly CodeDirectory $codeDirectory
|
|
) {
|
|
}
|
|
|
|
public function generate(): Code
|
|
{
|
|
do {
|
|
$code = new Code(
|
|
$this->generateRandomString(Code::LENGTH)
|
|
);
|
|
} while ($this->exists($code));
|
|
|
|
return $code;
|
|
}
|
|
|
|
private function generateRandomString(int $length): string
|
|
{
|
|
$dictionary = implode(
|
|
'',
|
|
array_unique(str_split(Code::ALLOWED_CHARACTERS))
|
|
);
|
|
|
|
$dictionaryLength = strlen($dictionary);
|
|
$randomString = '';
|
|
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$randomString .= $dictionary[random_int(0, $dictionaryLength - 1)];
|
|
}
|
|
|
|
return $randomString;
|
|
}
|
|
|
|
private function exists(Code $code): bool
|
|
{
|
|
return $this->codeDirectory->exists($code);
|
|
}
|
|
}
|