<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;

class AppendSqlToResponse
{
private $sql = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!env('APP_DEBUG')) {
return $next($request);
}
// inject
DB::listen(function (QueryExecuted $query) {
if (count($this->sql) < 10) {
$sql = $query->sql;
if (!empty($query->bindings)) {
foreach ($query->bindings as $key => $binding) {
// This regex matches placeholders only, not the question marks,
// nested in quotes, while we iterate through the bindings
// and substitute placeholders by suitable values.
$regex = is_numeric($key)
? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
: "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";

// Mimic bindValue and only quote non-integer and non-float data types
if (!is_int($binding) && !is_float($binding)) {
$binding = utf8_to_unicode($binding);
$binding = $query->connection->getPdo()->quote($binding);
}

$sql = preg_replace($regex, $binding, $sql, 1);
}
}
$this->sql[] = $sql;
}
// $query->bindings
// $query->time
});
$response = $next($request);
// set headers
foreach ($this->sql as $k => $sql) {
$response->headers->set(sprintf("X-SQL-%02d", $k), $sql);
}
return $response;
}
}

    function utf8_to_unicode($str = '')
{
$encoding = 'UTF-8';
$prefix = '\\u';
$postfix = '';
$str = iconv($encoding, 'UCS-2', $str);
$arrstr = str_split($str, 2);
$unistr = '';
for ($i = 0, $len = count($arrstr); $i < $len; $i++) {
// for linux
$rawByte = str_split($arrstr[$i], 1);
$dec = bin2hex($rawByte[1] . $rawByte[0]);
$unistr .= $prefix . $dec . $postfix;
}
return $unistr;
}

Laravel返回SQL语句中间件_linux