|
- <?php
-
- namespace App\Util;
-
- use App\Features\InstanceAble;
- use Illuminate\Support\Facades\DB;
- use LogicException;
-
- class DBUtil
- {
- use InstanceAble;
-
- private bool $isBeginning = false;
-
- public function __destruct()
- {
- if ($this->isBeginning) {
- $this->rollBack();
- }
- }
-
- public function beginTransaction(): void
- {
- if ($this->isBeginning) {
- throw new LogicException("2重トランザクション開始検知");
- }
-
- DB::beginTransaction();
- $this->isBeginning = true;
- }
-
- public function commit(): void
- {
- if (!$this->isBeginning) {
- throw new LogicException("無効なコミット検知");
- }
- DB::commit();
- $this->isBeginning = false;
- }
-
- public function rollBack(): void
- {
- if (!$this->isBeginning) {
- throw new LogicException("無効なロールバック検知");
- }
-
- DB::rollBack();
- $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
- foreach ($trace as $line) {
- logger(sprintf(
- "Rollback from File:%s Line:%d",
- data_get($line, "file", ""),
- data_get($line, "line", 0)
- ));
- }
- logs()->warning("ロールバック検知");
- $this->isBeginning = false;
- }
-
- public function isBeginning(): bool
- {
- return $this->isBeginning;
- }
- }
|