<?php

namespace Velis\Db;

use Closure;
use Velis\App;

/**
 * @author Łukasz Gąsiorek <lukasz.gasiorek@velistech.com>
 */
trait TransactionBlockTrait
{
    /**
     * @throws Exception
     */
    public function startTransactionBlock(Closure $fn)
    {
        // To let us use Db instance that was injected into the class
        if (property_exists($this, 'db') && $this->db instanceof Db) {
            $db = $this->db;
        } else {
            /** @var Db $db */
            $db = App::getService('db');
        }

        $commit = $db->startTrans();

        try {
            $ret = $fn($db);

            if ($commit) {
                $db->commit();
            }

            return $ret;
        } catch (Exception $e) {
            if ($commit) {
                $db->rollback();
            }

            throw $e;
        }
    }
}
