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