]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/front/ShaarliMiddleware.php
Use multi-level routes for existing controllers instead of 1 level everywhere
[github/shaarli/Shaarli.git] / application / front / ShaarliMiddleware.php
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 $this->container->basePath = rtrim($request->getUri()->getBasePath(), '/');
42
43 try {
44 $response = $next($request, $response);
45 } catch (ShaarliFrontException $e) {
46 $this->container->pageBuilder->assign('message', $e->getMessage());
47 if ($this->container->conf->get('dev.debug', false)) {
48 $this->container->pageBuilder->assign(
49 'stacktrace',
50 nl2br(get_class($this) .': '. $e->getTraceAsString())
51 );
52 }
53
54 $response = $response->withStatus($e->getCode());
55 $response = $response->write($this->container->pageBuilder->render('error'));
56 } catch (UnauthorizedException $e) {
57 return $response->withRedirect($this->container->basePath . '/login');
58 }
59
60 return $response;
61 }
62 }