Created
November 24, 2020 14:10
-
-
Save alsma/b5ac6f77e5e0fa9d64c20234243b535c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
declare(strict_types=1); | |
namespace App\Transactional; | |
use Illuminate\{ | |
Database\DatabaseManager, | |
}; | |
class TransactionalExecutor | |
{ | |
private DatabaseManager $databaseManager; | |
private array $pendingCallbacks = []; | |
public function __construct(DatabaseManager $databaseManager) | |
{ | |
$this->databaseManager = $databaseManager; | |
} | |
public function execute(callable $callback): void | |
{ | |
if (!$this->databaseManager->transactionLevel()) { | |
$callback(); | |
return; | |
} | |
$this->pendingCallbacks[] = \Closure::fromCallable($callback); | |
} | |
public function forget(): void | |
{ | |
$this->pendingCallbacks = []; | |
} | |
public function handleTransactionCommit(): void | |
{ | |
$callbacks = collect($this->pendingCallbacks); | |
$this->forget(); | |
$callbacks->reverse()->each->__invoke(); | |
} | |
public function handleTransactionRollback(): void | |
{ | |
$this->forget(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment