xref: /webtrees/app/Http/Middleware/UseTransaction.php (revision ccb0284c0506d1c862df94d76a9eed868a22e6cc)
1*ccb0284cSGreg Roach<?php
2*ccb0284cSGreg Roach/**
3*ccb0284cSGreg Roach * webtrees: online genealogy
4*ccb0284cSGreg Roach * Copyright (C) 2018 webtrees development team
5*ccb0284cSGreg Roach * This program is free software: you can redistribute it and/or modify
6*ccb0284cSGreg Roach * it under the terms of the GNU General Public License as published by
7*ccb0284cSGreg Roach * the Free Software Foundation, either version 3 of the License, or
8*ccb0284cSGreg Roach * (at your option) any later version.
9*ccb0284cSGreg Roach * This program is distributed in the hope that it will be useful,
10*ccb0284cSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
11*ccb0284cSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12*ccb0284cSGreg Roach * GNU General Public License for more details.
13*ccb0284cSGreg Roach * You should have received a copy of the GNU General Public License
14*ccb0284cSGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
15*ccb0284cSGreg Roach */
16*ccb0284cSGreg Roachdeclare(strict_types=1);
17*ccb0284cSGreg Roach
18*ccb0284cSGreg Roachnamespace Fisharebest\Webtrees\Http\Middleware;
19*ccb0284cSGreg Roach
20*ccb0284cSGreg Roachuse Closure;
21*ccb0284cSGreg Roachuse Fisharebest\Webtrees\Database;
22*ccb0284cSGreg Roachuse Symfony\Component\HttpFoundation\Request;
23*ccb0284cSGreg Roachuse Symfony\Component\HttpFoundation\Response;
24*ccb0284cSGreg Roachuse Throwable;
25*ccb0284cSGreg Roach
26*ccb0284cSGreg Roach/**
27*ccb0284cSGreg Roach * Middleware to wrap a request in a transaction.
28*ccb0284cSGreg Roach */
29*ccb0284cSGreg Roachclass UseTransaction {
30*ccb0284cSGreg Roach	/**
31*ccb0284cSGreg Roach	 * @param Request $request
32*ccb0284cSGreg Roach	 * @param Closure $next
33*ccb0284cSGreg Roach	 *
34*ccb0284cSGreg Roach	 * @return Response
35*ccb0284cSGreg Roach	 * @throws Throwable
36*ccb0284cSGreg Roach	 */
37*ccb0284cSGreg Roach	public function handle(Request $request, Closure $next): Response {
38*ccb0284cSGreg Roach		throw new Throwable('eek');
39*ccb0284cSGreg Roach		$connected = Database::isConnected();
40*ccb0284cSGreg Roach		if ($connected) {
41*ccb0284cSGreg Roach			Database::beginTransaction();
42*ccb0284cSGreg Roach		}
43*ccb0284cSGreg Roach		try {
44*ccb0284cSGreg Roach			$response = $next($request);
45*ccb0284cSGreg Roach
46*ccb0284cSGreg Roach			if ($connected) {
47*ccb0284cSGreg Roach				Database::commit();
48*ccb0284cSGreg Roach			}
49*ccb0284cSGreg Roach		} catch (Throwable $ex) {
50*ccb0284cSGreg Roach			if ($connected) {
51*ccb0284cSGreg Roach				Database::rollBack();
52*ccb0284cSGreg Roach
53*ccb0284cSGreg Roach				throw $ex;
54*ccb0284cSGreg Roach			}
55*ccb0284cSGreg Roach		}
56*ccb0284cSGreg Roach
57*ccb0284cSGreg Roach		return $response;
58*ccb0284cSGreg Roach	}
59*ccb0284cSGreg Roach}
60