<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/5 13:32
 * @Description：
 *
 */
namespace Application\Service\DB;

use Application\Common\Container;
use Application\Common\Crypt;
use Application\Service\BaseService;
use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Exception\RuntimeException;
use Laminas\Db\TableGateway\TableGateway;
use phpDocumentor\Reflection\Types\Mixed;
use Laminas\Db\Sql\Sql;
use Laminas\Validator\Db\NoRecordExists;
use Laminas\Validator\Exception\InvalidArgumentException;

class Db extends BaseService
{
    /**
     * 是否开启事务
     * @var bool
     */
    public static bool $isTransaction = false;

    /**
     * 事务列表
     * @var array
     */
    public static array $transactionMap = [];

    public function __destruct()
    {
        self::rollback();
    }

    public static function isInTransaction(): bool
    {
        return self::$isTransaction;
    }

    /**
     * 还没写完
     */
    public static function beginTransaction()
    {
        if (defined('IS_UNIT_TEST')) {
            return;
        }

        self::$isTransaction = true;
    }

    public static function commit()
    {
        if (defined('IS_UNIT_TEST')) {
            return;
        }

        foreach (self::$transactionMap as $key => $item) {
            $item->getDriver()->getConnection()->commit();
            unset(self::$transactionMap[$key]);
        }

        if (defined('IS_UNIT_TEST')) {
            return;
        }
        self::$isTransaction = false;
    }

    public static function rollback()
    {
        foreach (self::$transactionMap as $key => $item) {
            if ($item->getDriver()->getConnection()->inTransaction()) {
                $item->getDriver()->getConnection()->rollback();
                unset(self::$transactionMap[$key]);
            }
        }


        if (defined('IS_UNIT_TEST')) {
            return;
        }
        self::$isTransaction = false;
    }


}