|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
/** |
|
5
|
|
|
* BEdita, API-first content management framework |
|
6
|
|
|
* Copyright 2017-2022 ChannelWeb Srl, Chialab Srl |
|
7
|
|
|
* |
|
8
|
|
|
* This file is part of BEdita: you can redistribute it and/or modify |
|
9
|
|
|
* it under the terms of the GNU Lesser General Public License as published |
|
10
|
|
|
* by the Free Software Foundation, either version 3 of the License, or |
|
11
|
|
|
* (at your option) any later version. |
|
12
|
|
|
* |
|
13
|
|
|
* See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details. |
|
14
|
|
|
*/ |
|
15
|
|
|
namespace BEdita\DevTools\Middleware; |
|
16
|
|
|
|
|
17
|
|
|
use Cake\Http\ServerRequest; |
|
18
|
|
|
use Cake\View\ViewVarsTrait; |
|
19
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
20
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
21
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
22
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Intercept HTML requests and render an user-friendly view. |
|
26
|
|
|
* |
|
27
|
|
|
* @since 4.0.0 |
|
28
|
|
|
*/ |
|
29
|
|
|
class HtmlMiddleware implements MiddlewareInterface |
|
30
|
|
|
{ |
|
31
|
|
|
use ViewVarsTrait; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @inheritDoc |
|
35
|
|
|
*/ |
|
36
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
37
|
|
|
{ |
|
38
|
|
|
if (!($request instanceof ServerRequest) || !$request->is('html')) { |
|
39
|
|
|
// Not an HTML request, or unable to detect easily. |
|
40
|
|
|
return $handler->handle($request); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
// Set correct "Accept" header, and proceed as usual. |
|
44
|
|
|
$request = $request->withHeader('Accept', 'application/vnd.api+json'); |
|
45
|
|
|
|
|
46
|
|
|
/** @var \Cake\Http\Response $response */ |
|
47
|
|
|
$response = $handler->handle($request); |
|
48
|
|
|
|
|
49
|
|
|
if (!in_array($response->getHeaderLine('Content-Type'), ['application/json', 'application/vnd.api+json'])) { |
|
50
|
|
|
// Not a JSON response. |
|
51
|
|
|
return $response; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
// Prepare HTML rendering. |
|
55
|
|
|
$this->viewBuilder() |
|
56
|
|
|
->setPlugin('BEdita/DevTools') |
|
57
|
|
|
->setLayout('html') |
|
58
|
|
|
->setTemplatePath('Common') |
|
59
|
|
|
->setTemplate('html'); |
|
60
|
|
|
$this->set(compact('request', 'response')); |
|
61
|
|
|
$view = $this->createView(); |
|
62
|
|
|
|
|
63
|
|
|
return $response |
|
64
|
|
|
->withType('html') |
|
65
|
|
|
->withStringBody($view->render()); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|