<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
        if ($this->app->environment() !== 'production') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        //Schema::defaultStringLength(191);
        app('Dingo\Api\Exception\Handler')->register(function (\Exception $exception) {
            $request = \Illuminate\Http\Request::capture();
            return app('App\Exceptions\Handler')->render($request, $exception);
        });

        // 打印所有sql
        if(config('app.db_log')) {
            \DB::listen(function($query) {
                // 先替换sql中的 % 避免 vsprintf 当成参数解析报错  Too few arguments
                $tmp = str_replace('%', '(no-vsprintf)', $query->sql);
                // \Log::info($tmp);
                $tmp = str_replace('?', '"'.'%s'.'"', $tmp);
                // \Log::info($tmp);
                $tmp = vsprintf($tmp, $query->bindings);
                $tmp = str_replace("\\","",$tmp);
                // 还原 %
                $tmp = str_replace('(no-vsprintf)', '%', $tmp);
                \Log::info($tmp);
                //Log::info($tmp."\n\n\t");
            });
        }
    }
}
