master

laravel/framework

Last updated at: 29/12/2023 09:23

DatabaseTransactions.php

TLDR

The DatabaseTransactions.php file contains a trait called DatabaseTransactions. This trait provides methods for handling database transactions on the specified connections.

Methods

beginDatabaseTransaction

This method handles database transactions on the specified connections. It initializes a new instance of the DatabaseTransactionsManager class and sets it as an instance in the container. It then begins a transaction on each connection specified in the connectionsToTransact method. Lastly, it registers a callback to roll back the transactions and disconnect from the connections before the application is destroyed.

connectionsToTransact

This method returns an array of the database connections that should have transactions. It checks if the connectionsToTransact property exists and returns its value if true, otherwise it returns an array with a null value.

<?php

namespace Illuminate\Foundation\Testing;

trait DatabaseTransactions
{
    /**
     * Handle database transactions on the specified connections.
     *
     * @return void
     */
    public function beginDatabaseTransaction()
    {
        $database = $this->app->make('db');

        $this->app->instance('db.transactions', $transactionsManager = new DatabaseTransactionsManager);

        foreach ($this->connectionsToTransact() as $name) {
            $connection = $database->connection($name);
            $connection->setTransactionManager($transactionsManager);
            $dispatcher = $connection->getEventDispatcher();

            $connection->unsetEventDispatcher();
            $connection->beginTransaction();
            $connection->setEventDispatcher($dispatcher);
        }

        $this->beforeApplicationDestroyed(function () use ($database) {
            foreach ($this->connectionsToTransact() as $name) {
                $connection = $database->connection($name);
                $dispatcher = $connection->getEventDispatcher();

                $connection->unsetEventDispatcher();
                $connection->rollBack();
                $connection->setEventDispatcher($dispatcher);
                $connection->disconnect();
            }
        });
    }

    /**
     * The database connections that should have transactions.
     *
     * @return array
     */
    protected function connectionsToTransact()
    {
        return property_exists($this, 'connectionsToTransact')
                            ? $this->connectionsToTransact : [null];
    }
}