-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add FreezesUuidTrait to help with unit tests
- Loading branch information
Showing
2 changed files
with
126 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Xthiago\ValueObject\Id\Testing; | ||
|
||
use ArrayIterator; | ||
use Iterator; | ||
use Ramsey\Uuid\Uuid; | ||
use \Ramsey\Uuid\UuidInterface; | ||
use Ramsey\Uuid\UuidFactory; | ||
use RuntimeException; | ||
|
||
trait FreezesUuidTrait | ||
{ | ||
private function freezeUuidV4WithFixedValue(string $uuid): void | ||
{ | ||
$factory = new class($uuid) extends UuidFactory { | ||
/** @var string */ | ||
private $uuid; | ||
|
||
public function __construct(string $uuid) | ||
{ | ||
$this->uuid = $uuid; | ||
parent::__construct(); | ||
} | ||
|
||
public function uuid4(): UuidInterface | ||
{ | ||
return Uuid::fromString($this->uuid); | ||
} | ||
}; | ||
|
||
Uuid::setFactory($factory); | ||
} | ||
|
||
private function freezeUuidV4WithKnownSequence(string ...$uuids): void | ||
{ | ||
$sequence = new ArrayIterator($uuids); | ||
$factory = new class($sequence) extends UuidFactory { | ||
/** @var Iterator */ | ||
private $uuidSequence; | ||
|
||
public function __construct(Iterator $uuidSequence) | ||
{ | ||
$this->uuidSequence = $uuidSequence; | ||
parent::__construct(); | ||
} | ||
|
||
public function uuid4(): UuidInterface | ||
{ | ||
if (false === $this->uuidSequence->valid()) { | ||
throw new RuntimeException( | ||
'The UUID sequence are over. Maybe more UUIDs were used than initially configured.' | ||
); | ||
} | ||
$uuid = $this->uuidSequence->current(); | ||
$this->uuidSequence->next(); | ||
|
||
return Uuid::fromString($uuid); | ||
} | ||
}; | ||
|
||
Uuid::setFactory($factory); | ||
} | ||
|
||
private function unfreezeUuid(): void | ||
{ | ||
Uuid::setFactory(new UuidFactory()); | ||
} | ||
} |