Skip to content

Commit

Permalink
Add ability to return the results of callable
Browse files Browse the repository at this point in the history
This adds the ability to return the results of a callable rather than an instance of `Ray`. If the closure has a return type, assume that the results of the callable should be return rather than `Ray`.
  • Loading branch information
grantholle committed Sep 2, 2023
1 parent 4088156 commit f95714f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/Ray.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Illuminate\Support\Testing\Fakes\MailFake;
use Illuminate\Testing\TestResponse;
use Illuminate\View\View;
use ReflectionFunction;
use Spatie\LaravelRay\Payloads\EnvironmentPayload;
use Spatie\LaravelRay\Payloads\ExecutedQueryPayload;
use Spatie\LaravelRay\Payloads\LoggedMailPayload;
Expand Down Expand Up @@ -304,7 +305,7 @@ public function countQueries(callable $callable)
$watcher->doNotSendIndividualQueries();
}

$this->handleWatcherCallable($watcher, $callable);
$output = $this->handleWatcherCallable($watcher, $callable);

$executedQueryStatistics = collect($watcher->getExecutedQueries())

Expand All @@ -324,6 +325,8 @@ public function countQueries(callable $callable)
->sendIndividualQueries();

$this->table($executedQueryStatistics, 'Queries');

return $output;
}

public function queries($callable = null)
Expand Down Expand Up @@ -431,7 +434,7 @@ public function stopShowingHttpClientRequests(): self
return $this;
}

protected function handleWatcherCallable(Watcher $watcher, Closure $callable = null): RayProxy
protected function handleWatcherCallable(Watcher $watcher, Closure $callable = null)
{
$rayProxy = new RayProxy();

Expand All @@ -444,11 +447,15 @@ protected function handleWatcherCallable(Watcher $watcher, Closure $callable = n
}

if ($callable) {
$callable();
$output = $callable();

if (! $wasEnabled) {
$watcher->disable();
}

if ($output && (new ReflectionFunction($callable))->hasReturnType()) {
return $output;
}
}

return $rayProxy;
Expand Down
10 changes: 10 additions & 0 deletions tests/Unit/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@
expect($this->client->sentRequests())->toHaveCount(1);
});

it('can log all queries in a callable and gets results', function () {
$results = ray()->showQueries(function (): \Illuminate\Support\Collection {
// will be logged
return DB::table('users')->where('id', 1)->get();
});
expect($this->client->sentRequests())->toHaveCount(1);
expect($results)->toBeInstanceOf(\Illuminate\Support\Collection::class);
expect($results->count())->toEqual(0);
});

it('show queries can be colorized', function () {
$this->useRealUuid();

Expand Down

0 comments on commit f95714f

Please sign in to comment.