Skip to content

Instantly share code, notes, and snippets.

@odan
Last active February 16, 2022 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odan/30c525f1144bd9e41547e44db9cbf0f8 to your computer and use it in GitHub Desktop.
Save odan/30c525f1144bd9e41547e44db9cbf0f8 to your computer and use it in GitHub Desktop.
Mock Ramsey\Uuid

Mock Ramsey\Uuid

The mock trait

<?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);
    }
}

Usage

$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
@Bastianowicz
Copy link

love you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment