]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | ||
3 | namespace Shaarli\Front; | |
4 | ||
5 | use Shaarli\Container\ShaarliContainer; | |
6 | use Shaarli\Front\Exception\ShaarliFrontException; | |
7 | use Shaarli\Front\Exception\UnauthorizedException; | |
8 | use Slim\Http\Request; | |
9 | use Slim\Http\Response; | |
10 | ||
11 | /** | |
12 | * Class ShaarliMiddleware | |
13 | * | |
14 | * This will be called before accessing any Shaarli controller. | |
15 | */ | |
16 | class ShaarliMiddleware | |
17 | { | |
18 | /** @var ShaarliContainer contains all Shaarli DI */ | |
19 | protected $container; | |
20 | ||
21 | public function __construct(ShaarliContainer $container) | |
22 | { | |
23 | $this->container = $container; | |
24 | } | |
25 | ||
26 | /** | |
27 | * Middleware execution: | |
28 | * - execute the controller | |
29 | * - return the response | |
30 | * | |
31 | * In case of error, the error template will be displayed with the exception message. | |
32 | * | |
33 | * @param Request $request Slim request | |
34 | * @param Response $response Slim response | |
35 | * @param callable $next Next action | |
36 | * | |
37 | * @return Response response. | |
38 | */ | |
39 | public function __invoke(Request $request, Response $response, callable $next) | |
40 | { | |
41 | try { | |
42 | $response = $next($request, $response); | |
43 | } catch (ShaarliFrontException $e) { | |
44 | $this->container->pageBuilder->assign('message', $e->getMessage()); | |
45 | if ($this->container->conf->get('dev.debug', false)) { | |
46 | $this->container->pageBuilder->assign( | |
47 | 'stacktrace', | |
48 | nl2br(get_class($this) .': '. $e->getTraceAsString()) | |
49 | ); | |
50 | } | |
51 | ||
52 | $response = $response->withStatus($e->getCode()); | |
53 | $response = $response->write($this->container->pageBuilder->render('error')); | |
54 | } catch (UnauthorizedException $e) { | |
55 | return $response->withRedirect($request->getUri()->getBasePath() . '/login'); | |
56 | } | |
57 | ||
58 | return $response; | |
59 | } | |
60 | } |