Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. # Mock Ramsey\Uuid
  2.  
  3. ## The mock method
  4.  
  5. ```php
  6. use Ramsey\Uuid\Generator\RandomGeneratorInterface;
  7. use Ramsey\Uuid\Uuid;
  8. use RuntimeException;
  9. // ...
  10.  
  11. /**
  12. * Sets the expected responses from `Uuid::uuid4()`.
  13. *
  14. * @param string[] $uuids An array of string representations of Uuids
  15. */
  16. protected function mockUuidValues(array $uuids)
  17. {
  18. $uuidFactory = new \Ramsey\Uuid\UuidFactory();
  19.  
  20. $uuidFactory->setRandomGenerator(new class($uuids) implements RandomGeneratorInterface
  21. {
  22. private $stack = [];
  23.  
  24. public function __construct(array $uuids)
  25. {
  26. $this->stack = array_map(function ($uuid) {
  27. return Uuid::fromString($uuid)->getBytes();
  28. }, $uuids);
  29. }
  30.  
  31. public function generate($length)
  32. {
  33. if (empty($this->stack)) {
  34. // throw new RuntimeException('The uuid stack is empty');
  35.  
  36. return Uuid::fromString(sprintf(
  37. '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  38. random_int(0, 65535),
  39. random_int(0, 65535),
  40. random_int(0, 65535),
  41. random_int(0, 4095) | 0x4000,
  42. random_int(0, 0x3fff) | 0x8000,
  43. random_int(0, 65535),
  44. random_int(0, 65535),
  45. random_int(0, 65535)
  46. ))->getBytes();
  47. }
  48.  
  49. return array_shift($this->stack);
  50. }
  51. });
  52.  
  53. \Ramsey\Uuid\Uuid::setFactory($uuidFactory);
  54. }
  55. ```
  56.  
  57. ### Usage
  58.  
  59. ```php
  60. $this->mockUuidValues([
  61. '3b2f5ae1-8be8-4738-a09b-e14a4c06fb8c',
  62. 'ceb1d076-2bd8-40ac-8a37-86aa3903a486',
  63. '21fc39e0-28f3-4fb7-8ebe-35ceba715cfb',
  64. ]);
  65.  
  66. $value1 = Uuid::uuid4()->toString(); // 3b2f5ae1-8be8-4738-a09b-e14a4c06fb8c
  67. $value2 = Uuid::uuid4()->toString(); // ceb1d076-2bd8-40ac-8a37-86aa3903a486
  68. $value3 = Uuid::uuid4()->toString(); // 21fc39e0-28f3-4fb7-8ebe-35ceba715cfb
  69. $value4 = Uuid::uuid4()->toString(); // RuntimeException The uuid stack is empty
  70. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement