-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecuteInUnitOfWork.php
More file actions
53 lines (47 loc) · 1.54 KB
/
ExecuteInUnitOfWork.php
File metadata and controls
53 lines (47 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/*
* Copyright 2025 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
declare(strict_types=1);
namespace CloudCreativity\Modules\Application\Bus\Middleware;
use Closure;
use CloudCreativity\Modules\Application\Bus\Exceptions\AbortOnFailureException;
use CloudCreativity\Modules\Contracts\Application\Bus\CommandMiddleware;
use CloudCreativity\Modules\Contracts\Application\UnitOfWork\UnitOfWorkManager;
use CloudCreativity\Modules\Contracts\Toolkit\Messages\Command;
use CloudCreativity\Modules\Contracts\Toolkit\Result\Result;
final readonly class ExecuteInUnitOfWork implements CommandMiddleware
{
/**
* ExecuteInUnitOfWork constructor.
*
* @param UnitOfWorkManager $unitOfWorkManager
* @param int $attempts
*/
public function __construct(
private UnitOfWorkManager $unitOfWorkManager,
private int $attempts = 1,
) {
}
/**
* @inheritDoc
*/
public function __invoke(Command $command, Closure $next): Result
{
try {
return $this->unitOfWorkManager->execute(
static function () use ($command, $next): Result {
$res = $next($command);
return $res->didSucceed() ? $res : throw new AbortOnFailureException($res);
},
$this->attempts,
);
} catch (AbortOnFailureException $ex) {
return $ex->getResult();
}
}
}