Skip to content

Commit 826c385

Browse files
committed
optimize allocates
1 parent 69888fb commit 826c385

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/Services/AtomicService.php

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,33 +37,35 @@ public function __construct(
3737
*/
3838
public function blocks(array $objects, callable $callback): mixed
3939
{
40+
/** @var array<string, \Bavix\Wallet\Models\Wallet> $blockObjects */
4041
$blockObjects = [];
4142
foreach ($objects as $object) {
4243
$wallet = $this->castService->getWallet($object);
4344
if (! $this->lockService->isBlocked($wallet->uuid)) {
44-
$blockObjects[] = $object;
45+
$blockObjects[$wallet->uuid] = $wallet;
4546
}
4647
}
4748

49+
if ($blockObjects === []) {
50+
return $callback();
51+
}
52+
4853
$callable = function () use ($blockObjects, $callback) {
49-
foreach ($blockObjects as $object) {
50-
$wallet = $this->castService->getWallet($object);
51-
$this->stateService->fork($wallet->uuid, $this->bookkeeperService->amount($wallet));
54+
foreach ($blockObjects as $uuid => $wallet) {
55+
$this->stateService->fork($uuid, $this->bookkeeperService->amount($wallet));
5256
}
5357
return $this->databaseService->transaction($callback);
5458
};
5559

56-
foreach ($blockObjects as $object) {
57-
$wallet = $this->castService->getWallet($object);
58-
$callable = fn () => $this->lockService->block($wallet->uuid, $callable);
60+
foreach (array_keys($blockObjects) as $uuid) {
61+
$callable = fn () => $this->lockService->block($uuid, $callable);
5962
}
6063

6164
try {
6265
return $callable();
6366
} finally {
64-
foreach ($blockObjects as $object) {
65-
$wallet = $this->castService->getWallet($object);
66-
$this->stateService->drop($wallet->uuid);
67+
foreach (array_keys($blockObjects) as $uuid) {
68+
$this->stateService->drop($uuid);
6769
}
6870
}
6971
}

0 commit comments

Comments
 (0)