diff options
Diffstat (limited to 'application/front/ShaarliMiddleware.php')
-rw-r--r-- | application/front/ShaarliMiddleware.php | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/application/front/ShaarliMiddleware.php b/application/front/ShaarliMiddleware.php new file mode 100644 index 00000000..fa6c6467 --- /dev/null +++ b/application/front/ShaarliMiddleware.php | |||
@@ -0,0 +1,57 @@ | |||
1 | <?php | ||
2 | |||
3 | namespace Shaarli\Front; | ||
4 | |||
5 | use Shaarli\Container\ShaarliContainer; | ||
6 | use Shaarli\Front\Exception\ShaarliException; | ||
7 | use Slim\Http\Request; | ||
8 | use Slim\Http\Response; | ||
9 | |||
10 | /** | ||
11 | * Class ShaarliMiddleware | ||
12 | * | ||
13 | * This will be called before accessing any Shaarli controller. | ||
14 | */ | ||
15 | class ShaarliMiddleware | ||
16 | { | ||
17 | /** @var ShaarliContainer contains all Shaarli DI */ | ||
18 | protected $container; | ||
19 | |||
20 | public function __construct(ShaarliContainer $container) | ||
21 | { | ||
22 | $this->container = $container; | ||
23 | } | ||
24 | |||
25 | /** | ||
26 | * Middleware execution: | ||
27 | * - execute the controller | ||
28 | * - return the response | ||
29 | * | ||
30 | * In case of error, the error template will be displayed with the exception message. | ||
31 | * | ||
32 | * @param Request $request Slim request | ||
33 | * @param Response $response Slim response | ||
34 | * @param callable $next Next action | ||
35 | * | ||
36 | * @return Response response. | ||
37 | */ | ||
38 | public function __invoke(Request $request, Response $response, callable $next) | ||
39 | { | ||
40 | try { | ||
41 | $response = $next($request, $response); | ||
42 | } catch (ShaarliException $e) { | ||
43 | $this->container->pageBuilder->assign('message', $e->getMessage()); | ||
44 | if ($this->container->conf->get('dev.debug', false)) { | ||
45 | $this->container->pageBuilder->assign( | ||
46 | 'stacktrace', | ||
47 | nl2br(get_class($this) .': '. $e->getTraceAsString()) | ||
48 | ); | ||
49 | } | ||
50 | |||
51 | $response = $response->withStatus($e->getCode()); | ||
52 | $response = $response->write($this->container->pageBuilder->render('error')); | ||
53 | } | ||
54 | |||
55 | return $response; | ||
56 | } | ||
57 | } | ||