1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BeyondCode\InlineTranslation; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
|
7
|
|
|
class InlineTranslationMiddleware |
8
|
|
|
{ |
9
|
|
|
/** @var InlineTranslation */ |
10
|
|
|
private $inlineTranslation; |
11
|
|
|
|
12
|
|
|
public function __construct(InlineTranslation $inlineTranslation) |
13
|
|
|
{ |
14
|
|
|
$this->inlineTranslation = $inlineTranslation; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Handle an incoming request. |
19
|
|
|
* |
20
|
|
|
* @param Request $request |
21
|
|
|
* @param Closure $next |
22
|
|
|
* @return mixed |
23
|
|
|
*/ |
24
|
|
|
public function handle($request, Closure $next) |
25
|
|
|
{ |
26
|
|
|
if (! $this->inlineTranslation->isEnabled()) { |
27
|
|
|
return $next($request); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$this->inlineTranslation->boot(); |
31
|
|
|
|
32
|
|
|
$response = $next($request); |
33
|
|
|
|
34
|
|
|
if ($response->isRedirection()) { |
35
|
|
|
return $response; |
36
|
|
|
} elseif ( |
37
|
|
|
($response->headers->has('Content-Type') && |
38
|
|
|
strpos($response->headers->get('Content-Type'), 'html') === false) |
39
|
|
|
|| $request->getRequestFormat() !== 'html' |
40
|
|
|
|| $response->getContent() === false |
41
|
|
|
) { |
42
|
|
|
return $response; |
43
|
|
|
} elseif (is_null($response->exception)) { |
44
|
|
|
$this->injectTranslationView($response); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $response; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function injectTranslationView($response) |
51
|
|
|
{ |
52
|
|
|
$content = $response->getContent(); |
53
|
|
|
|
54
|
|
|
$renderedContent = view('inline-translation::translation'); |
55
|
|
|
|
56
|
|
|
$pos = strripos($content, '</body>'); |
57
|
|
|
|
58
|
|
|
if (false !== $pos) { |
59
|
|
|
$content = substr($content, 0, $pos) . $renderedContent . substr($content, $pos); |
60
|
|
|
} else { |
61
|
|
|
$content = $content . $renderedContent; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// Update the new content and reset the content length |
65
|
|
|
$response->setContent($content); |
66
|
|
|
$response->headers->remove('Content-Length'); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
} |