diff --git a/src/Telescope.php b/src/Telescope.php index 5169cdd0b..9a2e48001 100644 --- a/src/Telescope.php +++ b/src/Telescope.php @@ -34,6 +34,13 @@ class Telescope */ public static $filterBatchUsing = []; + /** + * The callback executed after queuing a new entry. + * + * @var \Closure + */ + public static $afterRecordingHook; + /** * The callback that adds tags to the record. * @@ -242,6 +249,10 @@ protected static function record(string $type, IncomingEntry $entry) if (collect(static::$filterUsing)->every->__invoke($entry)) { static::$entriesQueue[] = $entry; } + + if (static::$afterRecordingHook) { + call_user_func(static::$afterRecordingHook, new static); + } }); } @@ -469,6 +480,19 @@ public static function filterBatch(Closure $callback) return new static; } + /** + * Set the callback that will be executed after an entry is recorded in the queue. + * + * @param \Closure $callback + * @return static + */ + public static function afterRecording(Closure $callback) + { + static::$afterRecordingHook = $callback; + + return new static; + } + /** * Set the callback that adds tags to the record. * diff --git a/tests/Telescope/TelescopeTest.php b/tests/Telescope/TelescopeTest.php new file mode 100644 index 000000000..64205772c --- /dev/null +++ b/tests/Telescope/TelescopeTest.php @@ -0,0 +1,73 @@ +get('config')->set('telescope.watchers', [ + QueryWatcher::class => [ + 'enabled' => true, + 'slow' => 0.9, + ], + ]); + } + + protected function tearDown() + { + Telescope::$afterRecordingHook = null; + + parent::tearDown(); + } + + /** + * @test + */ + public function run_after_recording_callback() + { + Telescope::afterRecording(function () { + $this->count++; + }); + + $this->app->get('db')->table('telescope_entries')->count(); + + $this->app->get('db')->table('telescope_entries')->count(); + + $this->assertSame(2, $this->count); + } + + /** + * @test + */ + public function after_recording_callback_can_store_and_flush() + { + Telescope::afterRecording(function (Telescope $telescope) { + if (count($telescope::$entriesQueue) > 1) { + $repository = $this->app->make(EntriesRepository::class); + $telescope->store($repository); + } + }); + + $this->app->get('db')->table('telescope_entries')->count(); + + $this->assertCount(1, Telescope::$entriesQueue); + + $this->app->get('db')->table('telescope_entries')->count(); + + $this->assertCount(0, Telescope::$entriesQueue); + + $this->app->get('db')->table('telescope_entries')->count(); + + $this->assertCount(1, Telescope::$entriesQueue); + } +}