Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Middleware except #9

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});
Loading