. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Http\Middleware; use Fisharebest\Webtrees\Module\ModuleThemeInterface; use Fisharebest\Webtrees\Module\WebtreesTheme; use Fisharebest\Webtrees\Services\ModuleService; use Fisharebest\Webtrees\Session; use Fisharebest\Webtrees\Site; use Generator; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function app; /** * Middleware to select a theme. */ class UseTheme implements MiddlewareInterface { /** @var ModuleService */ private $module_service; /** * UseTheme constructor. * * @param ModuleService $module_service */ public function __construct(ModuleService $module_service) { $this->module_service = $module_service; } /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * * @return ResponseInterface */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { foreach ($this->themes() as $theme) { if ($theme instanceof ModuleThemeInterface) { app()->instance(ModuleThemeInterface::class, $theme); $request = $request->withAttribute('theme', $theme); Session::put('theme', $theme->name()); break; } } return $handler->handle($request); } /** * The theme can be chosen in various ways. * * @return Generator */ private function themes(): Generator { $themes = $this->module_service->findByInterface(ModuleThemeInterface::class); // Last theme used yield $themes->get(Session::get('theme')); // Default for site yield $themes->get(Site::getPreference('THEME_DIR')); // Default for application yield app(WebtreesTheme::class); } }