1<?php 2/** 3 * webtrees: online genealogy 4 * Copyright (C) 2019 webtrees development team 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16declare(strict_types=1); 17 18namespace Fisharebest\Webtrees\Http\Middleware; 19 20use Closure; 21use Fisharebest\Webtrees\Module\ModuleThemeInterface; 22use Fisharebest\Webtrees\Module\WebtreesTheme; 23use Fisharebest\Webtrees\Services\ModuleService; 24use Fisharebest\Webtrees\Session; 25use Fisharebest\Webtrees\Site; 26use Fisharebest\Webtrees\Tree; 27use Generator; 28use Symfony\Component\HttpFoundation\Request; 29use Symfony\Component\HttpFoundation\Response; 30use Throwable; 31 32/** 33 * Middleware to set a global theme. 34 */ 35class UseTheme implements MiddlewareInterface 36{ 37 /** @var ModuleService */ 38 private $module_service; 39 40 /** 41 * UseTheme constructor. 42 * 43 * @param ModuleService $module_service 44 */ 45 public function __construct(ModuleService $module_service) 46 { 47 $this->module_service = $module_service; 48 } 49 50 /** 51 * @param Request $request 52 * @param Closure $next 53 * 54 * @return Response 55 * @throws Throwable 56 */ 57 public function handle(Request $request, Closure $next): Response 58 { 59 foreach ($this->themes() as $theme) { 60 if ($theme instanceof ModuleThemeInterface) { 61 // Bind this theme into the container 62 app()->instance(ModuleThemeInterface::class, $theme); 63 64 // Remember this setting 65 Session::put('theme_id', $theme->name()); 66 67 break; 68 } 69 } 70 71 return $next($request); 72 } 73 74 /** 75 * The theme can be chosen in various ways. 76 * 77 * @return Generator 78 */ 79 private function themes(): Generator 80 { 81 $themes = $this->module_service->findByInterface(ModuleThemeInterface::class); 82 83 // Last theme used 84 yield $themes->get(Session::get('theme_id', '')); 85 86 // Default for tree 87 $tree = app()->make(Tree::class); 88 89 if ($tree instanceof Tree) { 90 yield $themes->get($tree->getPreference('THEME_DIR')); 91 } 92 93 // Default for site 94 yield $themes->get(Site::getPreference('THEME_DIR')); 95 96 // Default for application 97 yield app()->make(WebtreesTheme::class); 98 } 99} 100