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 all commits
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
83 changes: 83 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ Apply the middleware to your web routes by appending it in the `withMiddleware`
})
```

You can also apply the middleware to specific routes or groups:

```php
use Pirsch\Http\Middleware\TrackPageview;

Route::middleware(TrackPageview::class)->group(function () {
Route::get('/', function () {
return view('welcome');
});
});
```

#### Manually

If you want to manually track pageviews instead, you can use the `Pirsch::track()` method.
Expand All @@ -69,3 +81,74 @@ Pirsch::track(
],
);
```

### Filter pages

You can configure the `TrackPageview` middleware to exclude specific pages from being tracked.

On a specific rouute, you can exclude pages by adding a `except` property to the middleware class:

```php
use Pirsch\Http\Middleware\TrackPageview;

Route::middleware(TrackPageview::class.':url/to/exclude/*')->group(function () {
Route::get('/', function () {
return view('welcome');
});
});
```

Multiple urls can be excluded by separating them with a comma:

```php
use Pirsch\Http\Middleware\TrackPageview;

Route::middleware(TrackPageview::class.':url/to/exclude/*,url/to/exclude2/*')->group(function () {
Route::get('/', function () {
return view('welcome');
});
});
```

To exclude pages globally, you can create a new middleware that extends the `TrackPageview` middleware and add an `except` property:

```php
namespace App\Http\Middleware;

use Pirsch\Http\Middleware\TrackPageview as Middleware;

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

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

- `except` is an array with all URIs paths taht you want to exclude from tracking.
- `exceptHeaders` is an array with all Headers that you want to exclude from tracking.

Then replace the `TrackPageview` middleware with this one on your `bootstrap/app.php` middleware configuration:

```diff
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
- \Pirsch\Http\Middleware\TrackPageview::class,
+ \App\Http\Middleware\TrackPageview::class,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless the middleware is published your name space should probably remain \Pirsch\Http\Middleware\TrackPageview.

And one other small note is that this registration I think will only work with Laravel 11.

Laravel 10 and below would be in \App\Http\Kernel

You may need to bump the composer.json minimum framework version requirement.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless the middleware is published your name space should probably remain

No, this is your local file created just below, see line 116.

]);
})
```
64 changes: 57 additions & 7 deletions src/Http/Middleware/TrackPageview.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,74 @@

class TrackPageview
{
public function handle(Request $request, Closure $next): mixed
/**
* 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, string ...$excepts): mixed
{
$response = $next($request);

if ($response instanceof RedirectResponse) {
return $response;
}

if ($request->hasHeader('X-Livewire')) {
return $response;
if (! $this->inExceptArray($request, $excepts) &&
! $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, array $excepts = null): bool
{
foreach (empty($excepts) ? $this->except : $excepts as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}

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

return false;
}
}
30 changes: 26 additions & 4 deletions tests/TrackPageviewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

$this->get('/');

Pirsch::shouldNotHaveBeenCalled();
Pirsch::shouldNotHaveReceived('track');
});

it('skips Livewire', function () {
Expand All @@ -33,16 +33,38 @@

$this->get('/', ['X-Livewire' => 'true']);

Pirsch::shouldNotHaveBeenCalled();
Pirsch::shouldNotHaveReceived('track');
});

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

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

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

Pirsch::shouldNotHaveBeenCalled();
Pirsch::shouldNotHaveReceived('track');
});

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

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

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

Pirsch::shouldNotHaveReceived('track');
});

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

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

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

Pirsch::shouldNotHaveReceived('track');
});
Loading