<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use App\Facades\Servers\Logs\Log;
/**
 * SQL监听
 * 
 */
class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        try{
            // SQL语句
            $sql = str_replace("?", "%s", $event->sql);
            // 循环处理
            foreach ($event->bindings as $i => $binding) {
                // 如果是时间
                if ($binding instanceof \DateTime) {
                    $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                }else {
                    if (is_string($binding))  $event->bindings[$i] = $binding;
                }
            }
            // 格式化数据
            $log = vsprintf($sql, $event->bindings);
            // 不是生产环境记录sql日志
            if( config('app.env') != 'production' ) Log::log('sql',$log,[ 'RunTime:'.$event->time.'ms' ]);
        }catch (\Exception $e){

        }
    }
}
