| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Ray\AuraSqlModule; |
||
| 6 | |||
| 7 | use Aura\Sql\ExtendedPdoInterface; |
||
| 8 | use Override; |
||
| 9 | use PDOException; |
||
| 10 | use Ray\Aop\MethodInterceptor; |
||
| 11 | use Ray\Aop\MethodInvocation; |
||
| 12 | use Ray\AuraSqlModule\Annotation\Transactional; |
||
| 13 | use Ray\AuraSqlModule\Exception\RollbackException; |
||
| 14 | |||
| 15 | use function count; |
||
| 16 | |||
| 17 | final readonly class TransactionalInterceptor implements MethodInterceptor |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 18 | { |
||
| 19 | public function __construct(private ?ExtendedPdoInterface $pdo = null) |
||
| 20 | { |
||
| 21 | } |
||
| 22 | |||
| 23 | /** |
||
| 24 | * {@inheritDoc} |
||
| 25 | */ |
||
| 26 | #[Override] |
||
| 27 | public function invoke(MethodInvocation $invocation) |
||
| 28 | { |
||
| 29 | $method = $invocation->getMethod(); |
||
| 30 | $transactional = $method->getAnnotation(Transactional::class); |
||
| 31 | if ($transactional instanceof Transactional && count((array) $transactional->value) > 1) { |
||
| 32 | return (new PropTransaction())($invocation, $transactional); |
||
| 33 | } |
||
| 34 | |||
| 35 | if (! $this->pdo instanceof ExtendedPdoInterface) { |
||
| 36 | return $invocation->proceed(); |
||
| 37 | } |
||
| 38 | |||
| 39 | try { |
||
| 40 | $this->pdo->beginTransaction(); |
||
| 41 | $result = $invocation->proceed(); |
||
| 42 | $this->pdo->commit(); |
||
| 43 | } catch (PDOException $e) { |
||
| 44 | $this->pdo->rollBack(); |
||
| 45 | |||
| 46 | throw new RollbackException($e->getMessage(), 0, $e); |
||
| 47 | } |
||
| 48 | |||
| 49 | return $result; |
||
| 50 | } |
||
| 51 | } |
||
| 52 |