Skip to content

Commit

Permalink
Improve Middleware except
Browse files Browse the repository at this point in the history
  • Loading branch information
asbiin committed Mar 23, 2024
1 parent de4d703 commit 5892d64
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 6 deletions.
62 changes: 56 additions & 6 deletions src/Http/Middleware/TrackPageview.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@

class TrackPageview
{
/**
* The URIs that should be excluded from tracking.
*
* @var array<int,string>
*/
protected array $except = [
'telescope',
'horizon',
];

/**
* The Headers that should be excluded from tracking.
*
* @var array<int,string>
*/
protected array $exceptHeaders = [
'X-Livewire',
];

/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): mixed
{
$response = $next($request);
Expand All @@ -17,16 +39,44 @@ public function handle(Request $request, Closure $next): mixed
return $response;
}

if ($request->hasHeader('X-Livewire')) {
return $response;
if (! $this->inExceptArray($request) &&
! $this->inExceptHeadersArray($request)
) {
Pirsch::track();
}

if (str_starts_with($request->route()->uri, 'telescope/')) {
return $response;
return $response;
}

/**
* Determine if the request has a header that should not be tracked.
*/
protected function inExceptHeadersArray(Request $request): bool
{
foreach ($this->exceptHeaders as $except) {
if ($request->hasHeader($except)) {
return true;
}
}

Pirsch::track();
return false;
}

return $response;
/**
* Determine if the request has a URI that should not be tracked.
*/
protected function inExceptArray(Request $request): bool
{
foreach ($this->except as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}

if ($request->fullUrlIs($except) || $request->is($except)) {
return true;
}
}

return false;
}
}
11 changes: 11 additions & 0 deletions tests/TrackPageviewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,14 @@

Pirsch::shouldNotHaveBeenCalled();
});

it('skips Horizon', function () {
Pirsch::spy();

Route::middleware(TrackPageview::class)
->get('horizon/test', fn () => 'Hello World');

$this->get('/horizon/test');

Pirsch::shouldNotHaveBeenCalled();
});

0 comments on commit 5892d64

Please sign in to comment.