TelescopeServiceProvider.php 2.8 KB
<?php

namespace App\Providers;

use App\Models\SystemHttpLog;
use Arr;
use DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\EntryType;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Laravel\Telescope\TelescopeApplicationServiceProvider;
use Str;

class TelescopeServiceProvider extends TelescopeApplicationServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->hideSensitiveRequestDetails();

        $this->filter();
    }

    /**
     * Prevent sensitive request details from being logged by Telescope.
     */
    protected function hideSensitiveRequestDetails(): void
    {
        Telescope::hideRequestHeaders(['cookie', 'x-csrf-token', 'x-xsrf-token']);
    }

    /**
     * Register the Telescope gate.
     *
     * This gate determines who can access Telescope in non-local environments.
     */
    protected function gate(): void
    {
        Gate::define('viewTelescope', static fn() => true);
    }

    /**
     * @return void
     */
    protected function filter(): void
    {
        Telescope::filter(static function (IncomingEntry $entry) {
            if ($entry->type === EntryType::REQUEST) {
                $content = $entry->content;

                dispatch(static fn() => DB::table('system_http_logs')->insertOrIgnore([
                    'guard'      => Str::of($content['uri'])->ltrim('/')->before('/')->ucfirst()->whenEmpty(fn() => Str::of('Web'))?->toString(),
                    'user_id'    => Arr::get($content, 'user.id', 0),
                    'method'     => $content['method'],
                    'uri'        => Str::before($content['uri'], '?'),
                    'ip'         => $content['ip_address'],
                    'request'    => json_encode(['header' => $content['headers'], 'payload' => $content['payload']], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
                    'response'   => json_encode(is_string($content['response']) ? ['content' => $content['response']] : $content['response'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
                    'consume'    => $content['duration'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ]))->afterResponse();


                return true;
            }

            if ($entry->type === EntryType::MODEL && $entry->content['action'] === "created" && Str::contains($entry->content['model'], SystemHttpLog::class)) {
                return false;
            }


            return true;

//            return $entry->isReportableException() ||
//                $entry->isFailedRequest() ||
//                $entry->isFailedJob() ||
//                $entry->isScheduledTask() ||
//                $entry->hasMonitoredTag();
        });
    }
}