]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/front/ShaarliMiddleware.php
Initialize admin Slim controllers
[github/shaarli/Shaarli.git] / application / front / ShaarliMiddleware.php
CommitLineData
6c50a6cc
A
1<?php
2
3namespace Shaarli\Front;
4
5use Shaarli\Container\ShaarliContainer;
2899ebb5
A
6use Shaarli\Front\Exception\ShaarliFrontException;
7use Shaarli\Front\Exception\UnauthorizedException;
6c50a6cc
A
8use Slim\Http\Request;
9use Slim\Http\Response;
10
11/**
12 * Class ShaarliMiddleware
13 *
14 * This will be called before accessing any Shaarli controller.
15 */
16class 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);
2899ebb5 43 } catch (ShaarliFrontException $e) {
6c50a6cc
A
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'));
2899ebb5
A
54 } catch (UnauthorizedException $e) {
55 return $response->withRedirect($request->getUri()->getBasePath() . '/login');
6c50a6cc
A
56 }
57
58 return $response;
59 }
60}