<?php
namespace App\Test\Traits;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use RuntimeException;
/**
* Trait.
*/
trait UuidTestTrait
{
/**
* Sets the expected responses from `Uuid::uuid4()`.
*
* @param string[] $uuids An array of string representations of Uuids
*/
protected function mockUuidValues(array $uuids): void
{
$uuidFactory = new UuidFactory();
$uuidFactory->setRandomGenerator(
new class($uuids) implements RandomGeneratorInterface {
private array $stack = [];
public function __construct(array $uuids)
{
$this->stack = array_map(function ($uuid) {
return Uuid::fromString($uuid)->getBytes();
}, $uuids);
}
public function generate(int $length): string
{
if (empty($this->stack)) {
throw new RuntimeException('The UUID stack is empty');
}
return array_shift($this->stack);
}
}
);
Uuid::setFactory($uuidFactory);
}
}
$this->mockUuidValues([
'3b2f5ae1-8be8-4738-a09b-e14a4c06fb8c',
'ceb1d076-2bd8-40ac-8a37-86aa3903a486',
'21fc39e0-28f3-4fb7-8ebe-35ceba715cfb',
]);
$value1 = Uuid::uuid4()->toString(); // 3b2f5ae1-8be8-4738-a09b-e14a4c06fb8c
$value2 = Uuid::uuid4()->toString(); // ceb1d076-2bd8-40ac-8a37-86aa3903a486
$value3 = Uuid::uuid4()->toString(); // 21fc39e0-28f3-4fb7-8ebe-35ceba715cfb
$value4 = Uuid::uuid4()->toString(); // RuntimeException The uuid stack is empty
love you