diff --git a/README.md b/README.md index 8b01879..9a3bc53 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,11 @@ You can always choose your own strategy for generating numbers: $generator->setStrategy(); ``` +Protection duplicate number generation +-------------------------------------- + +This tool automatically protects you from generating a duplicate number. To protect you, an automatic lock (see the `baraja-core/lock` library for more information) is used, which allows only one number to be generated at a time, while competing processes in other threads are suspended in the meantime. + 📄 License ----------- diff --git a/composer.json b/composer.json index ad64dcd..0e4708f 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,8 @@ } ], "require": { - "php": "^8.0" + "php": "^8.0", + "baraja-core/lock": "^1.0" }, "require-dev": { "phpstan/phpstan": "^0.12.74", diff --git a/src/VariableGenerator.php b/src/VariableGenerator.php index 8f446de..0aabc25 100644 --- a/src/VariableGenerator.php +++ b/src/VariableGenerator.php @@ -5,6 +5,7 @@ namespace Baraja\VariableGenerator; +use Baraja\Lock\Lock; use Baraja\VariableGenerator\Order\DefaultOrderVariableLoader; use Baraja\VariableGenerator\Order\OrderEntity; use Baraja\VariableGenerator\Strategy\FormatStrategy; @@ -35,8 +36,10 @@ public function __construct( * Generate new variable symbol by last variable. * In case of invalid last symbol or init, use first valid symbol by specific strategy. */ - public function generate(?string $last = null): int + public function generate(?string $last = null, string $transactionName = 'variable-generator'): int { + Lock::wait($transactionName); + Lock::startTransaction($transactionName); $last ??= $this->variableLoader->getCurrent(); $new = $last === null ? $this->strategy->getFirst()