Skip to content

Commit 5892d64

Browse files
committed
Improve Middleware except
1 parent de4d703 commit 5892d64

File tree

2 files changed

+67
-6
lines changed

2 files changed

+67
-6
lines changed

src/Http/Middleware/TrackPageview.php

+56-6
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,28 @@
99

1010
class TrackPageview
1111
{
12+
/**
13+
* The URIs that should be excluded from tracking.
14+
*
15+
* @var array<int,string>
16+
*/
17+
protected array $except = [
18+
'telescope',
19+
'horizon',
20+
];
21+
22+
/**
23+
* The Headers that should be excluded from tracking.
24+
*
25+
* @var array<int,string>
26+
*/
27+
protected array $exceptHeaders = [
28+
'X-Livewire',
29+
];
30+
31+
/**
32+
* Handle an incoming request.
33+
*/
1234
public function handle(Request $request, Closure $next): mixed
1335
{
1436
$response = $next($request);
@@ -17,16 +39,44 @@ public function handle(Request $request, Closure $next): mixed
1739
return $response;
1840
}
1941

20-
if ($request->hasHeader('X-Livewire')) {
21-
return $response;
42+
if (! $this->inExceptArray($request) &&
43+
! $this->inExceptHeadersArray($request)
44+
) {
45+
Pirsch::track();
2246
}
2347

24-
if (str_starts_with($request->route()->uri, 'telescope/')) {
25-
return $response;
48+
return $response;
49+
}
50+
51+
/**
52+
* Determine if the request has a header that should not be tracked.
53+
*/
54+
protected function inExceptHeadersArray(Request $request): bool
55+
{
56+
foreach ($this->exceptHeaders as $except) {
57+
if ($request->hasHeader($except)) {
58+
return true;
59+
}
2660
}
2761

28-
Pirsch::track();
62+
return false;
63+
}
2964

30-
return $response;
65+
/**
66+
* Determine if the request has a URI that should not be tracked.
67+
*/
68+
protected function inExceptArray(Request $request): bool
69+
{
70+
foreach ($this->except as $except) {
71+
if ($except !== '/') {
72+
$except = trim($except, '/');
73+
}
74+
75+
if ($request->fullUrlIs($except) || $request->is($except)) {
76+
return true;
77+
}
78+
}
79+
80+
return false;
3181
}
3282
}

tests/TrackPageviewTest.php

+11
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,14 @@
4646

4747
Pirsch::shouldNotHaveBeenCalled();
4848
});
49+
50+
it('skips Horizon', function () {
51+
Pirsch::spy();
52+
53+
Route::middleware(TrackPageview::class)
54+
->get('horizon/test', fn () => 'Hello World');
55+
56+
$this->get('/horizon/test');
57+
58+
Pirsch::shouldNotHaveBeenCalled();
59+
});

0 commit comments

Comments
 (0)