Laravel返回SQL語句中間件

<?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;
    }

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章