<?php

/**
 * Database transaction
 *
 * @author: http://phpdao.com
 * @date: 27.11.2007
 */
class Transaction {

    private static $transactions;
    private $connection;

    public function Transaction() {
        $this->connection = new Connection();
        if (!Transaction::$transactions) {
            Transaction::$transactions = new ArrayList();
        }
        Transaction::$transactions->add($this);

        $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
        fwrite($myfile, 'BEGIN' . ";\r\n");
        fclose($myfile);

        $this->connection->executeQuery('BEGIN');
    }

    /**
     * Zakonczenie transakcji i zapisanie zmian
     */
    public function commit() {
        $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
        fwrite($myfile, 'COMMIT' . ";\r\n");
        fclose($myfile);

        $this->connection->executeQuery('COMMIT');
        $this->connection->close();
        Transaction::$transactions->removeLast();
    }

    /**
     * Zakonczenie transakcji i wycofanie zmian
     */
    public function rollback() {
        $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
        fwrite($myfile, 'ROLLBACK' . ";\r\n");
        fclose($myfile);

        $this->connection->executeQuery('ROLLBACK');
        $this->connection->close();
        Transaction::$transactions->removeLast();
    }

    /**
     * Pobranie polaczenia dla obencej transakcji
     *
     * @return polazenie do bazy
     */
    public function getConnection() {
        return $this->connection;
    }

    /**
     * Zwraca obecna transakcje
     *
     * @return transkacja
     */
    public static function getCurrentTransaction() {
        if (Transaction::$transactions) {
            $tran = Transaction::$transactions->getLast();
            return $tran;
        }
        return;
    }

}

?>