Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Mock Ramsey\Uuid
- ## The mock method
- ```php
- use Ramsey\Uuid\Generator\RandomGeneratorInterface;
- use Ramsey\Uuid\Uuid;
- use RuntimeException;
- // ...
- /**
- * Sets the expected responses from `Uuid::uuid4()`.
- *
- * @param string[] $uuids An array of string representations of Uuids
- */
- protected function mockUuidValues(array $uuids)
- {
- $uuidFactory = new \Ramsey\Uuid\UuidFactory();
- $uuidFactory->setRandomGenerator(new class($uuids) implements RandomGeneratorInterface
- {
- private $stack = [];
- public function __construct(array $uuids)
- {
- $this->stack = array_map(function ($uuid) {
- return Uuid::fromString($uuid)->getBytes();
- }, $uuids);
- }
- public function generate($length)
- {
- if (empty($this->stack)) {
- // throw new RuntimeException('The uuid stack is empty');
- return Uuid::fromString(sprintf(
- '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
- random_int(0, 65535),
- random_int(0, 65535),
- random_int(0, 65535),
- random_int(0, 4095) | 0x4000,
- random_int(0, 0x3fff) | 0x8000,
- random_int(0, 65535),
- random_int(0, 65535),
- random_int(0, 65535)
- ))->getBytes();
- }
- return array_shift($this->stack);
- }
- });
- \Ramsey\Uuid\Uuid::setFactory($uuidFactory);
- }
- ```
- ### Usage
- ```php
- $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
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement