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