File: D:/HostingSpaces/SBogers10/helder.komma.pro/app/Http/Middleware/CookieConsentMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Contracts\Foundation\Application;
class CookieConsentMiddleware
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function handle($request, Closure $next)
{
$response = $next($request);
if (! $response instanceof Response) {
return $response;
}
if (! $this->containsBodyTag($response)) {
return $response;
}
return $this->addCookieConsentScriptToResponse($response);
}
/**
* Add the cookie script before the closing body tag
*
* @param \Illuminate\Http\Response $response
* @return \Illuminate\Http\Response $response
*/
protected function addCookieConsentScriptToResponse(Response $response)
{
// Get content
$content = $response->getContent();
// Get closing body tag position
$closingBodyTagPosition = $this->getLastClosingBodyTagPosition($content);
// Add script to content
$newContent = '';
$newContent .= substr($content, 0, $closingBodyTagPosition);
$newContent .= view('site.partials.cookieIndex')->render();
$newContent .= substr($content, $closingBodyTagPosition);
return $response->setContent($newContent);
}
/**
* Check for body-tag
*
* @param Response $response
* @return bool
*/
protected function containsBodyTag(Response $response)
{
return $this->getLastClosingBodyTagPosition($response->getContent()) !== false;
}
/**
* Get position body tag
*
* @param string $content
* @return int
*/
protected function getLastClosingBodyTagPosition($content = '')
{
return strripos($content, '</body>');
}
}