Skip to content
Merged
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
32 changes: 32 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Tests

on:
push:
branches: [main]
pull_request:

jobs:
tests:
name: PHP ${{ matrix.php }} (${{ matrix.dependencies }})
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
php: ['8.5']
dependencies: [lowest, highest]

steps:
- uses: actions/checkout@v5

- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: curl, json, zlib
coverage: none

- uses: ramsey/composer-install@v3
with:
dependency-versions: ${{ matrix.dependencies }}

- run: vendor/bin/pest
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/vendor
/.phpunit.cache
/.idea
composer.lock
.DS_Store
58 changes: 29 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,93 +1,93 @@
# thepublicood.analytics for PHP
# thepublicgood.trace for PHP

Send page views, API requests and custom events to The Public Good Analytics from your server. Nothing runs in the browser.
Send page views, API requests and custom events to The Public Good Trace from your server. Nothing runs in the browser.

Requires PHP 8.3+ with the cURL extension. Works with any framework, and includes a Laravel integration.
Requires PHP 8.5+ with the cURL extension. Works with any framework, and includes a Laravel integration.

```bash
composer require thepublicgood/analytics
composer require thepublicgood/trace
```

## Laravel

Add your property key and endpoint to `.env`. Both are on the property's **Keys** page.
Add your property key to `.env`. It's on the property's **Keys** page.

```dotenv
ANALYTICS_KEY=ak_...
ANALYTICS_ENDPOINT=https://analytics.example.com/api/v1
TRACE_KEY=ak_...
```

If the analytics app runs locally with a self-signed certificate, set `ANALYTICS_VERIFY_SSL=false` in development. Leave it on in production.
Events go to `https://trace.thepublicgood.dev/api/v1`. If Trace is hosted elsewhere, set `TRACE_ENDPOINT` to the endpoint shown on the **Keys** page.

If the Trace app runs locally with a self-signed certificate, set `TRACE_VERIFY_SSL=false` in development. Leave it on in production.

Add the middleware to record every page view automatically:

```php
// bootstrap/app.php
use TPG\Analytics\Laravel\TrackVisits;
use TPG\Trace\Laravel\TrackVisits;

->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [TrackVisits::class]);
})
```

Page views are successful `GET` requests that return HTML or an Inertia page. Errors, JSON, prefetches and Inertia partial reloads are skipped. For an API, set `ANALYTICS_TRACK=requests` to record every request with its method, route pattern, status and duration instead.
Page views are successful `GET` requests that return HTML or an Inertia page. Errors, JSON, prefetches and Inertia partial reloads are skipped. For an API, set `TRACE_TRACK=requests` to record every request with its method, route pattern, status and duration instead.

Record custom events with the facade. The visitor comes from the current request:

```php
use TPG\Analytics\Laravel\Analytics;
use TPG\Trace\Laravel\Trace;

Analytics::event('signup', ['plan' => 'pro']);
Trace::event('signup', ['plan' => 'pro']);
```

Events are sent in one batch after the response has gone, so they don't slow your pages down. Events tracked in queued jobs and Artisan commands are sent when the job or command finishes.

Publish the config to change ignored paths or send signed-in users' IDs:

```bash
php artisan vendor:publish --tag=analytics-client-config
php artisan vendor:publish --tag=trace-client-config
```

### Testing

```php
$analytics = Analytics::fake();
$trace = Trace::fake();

$this->post('/signup');

expect(array_column($analytics->events(), 'name'))->toContain('signup');
expect(array_column($trace->events(), 'name'))->toContain('signup');
```

## Any PHP app

```php
use TPG\Analytics\Client;
use TPG\Analytics\Visitor;
use TPG\Trace\Client;
use TPG\Trace\Visitor;

$analytics = new Client(
key: 'ak_...',
endpoint: 'https://analytics.example.com/api/v1',
);
$trace = new Client(key: 'ak_...');

$visitor = Visitor::fromGlobals();

$analytics->pageview('https://example.com/pricing', $visitor, referrer: $_SERVER['HTTP_REFERER'] ?? null);
$analytics->event('signup', ['plan' => 'pro'], $visitor);
$analytics->request('GET', 'https://api.example.com/users/7', status: 200, durationMs: 35, visitor: $visitor, route: '/users/{user}');
$trace->pageview('https://example.com/pricing', $visitor, referrer: $_SERVER['HTTP_REFERER'] ?? null);
$trace->event('signup', ['plan' => 'pro'], $visitor);
$trace->request('GET', 'https://api.example.com/users/7', status: 200, durationMs: 35, visitor: $visitor, route: '/users/{user}');
```

Events are queued and sent in batches of 100, and whatever is left is sent when the script ends. Call `$analytics->flush()` to send them sooner, such as in a long-running worker.
If Trace is hosted elsewhere, pass the endpoint too: `new Client(key: 'ak_...', endpoint: 'https://trace.example.com/api/v1')`.

Events are queued and sent in batches of 100, and whatever is left is sent when the script ends. Call `$trace->flush()` to send them sooner, such as in a long-running worker.

### Visitors

Analytics uses the visitor's IP address and user agent to work out their location and device, and to count unique visitors. It never stores them.
Trace uses the visitor's IP address and user agent to work out their location and device, and to count unique visitors. It never stores them.

On properties with **persistent** visitor identification, give each visitor a first-party cookie so they are recognised when they come back:

```php
use TPG\Analytics\VisitorCookie;
use TPG\Trace\VisitorCookie;

$settings = $analytics->ping(); // Cache this.
$settings = $trace->ping(); // Cache this.

if ($settings->persistentVisitors && $visitor->anonymousId === null) {
$id = VisitorCookie::generate();
Expand All @@ -103,7 +103,7 @@ Pass a user ID with `$visitor->withUserId($user->id)` to count the same person o
Tracking never throws. Batches that can't be sent are retried once after network errors, rate limits and server errors, then dropped and passed to `onError`, or PHP's error log without one:

```php
new Client(key: '...', endpoint: '...', onError: function (AnalyticsException $exception, array $events) {
new Client(key: '...', onError: function (TraceException $exception, array $events) {
report($exception);
});
```
Expand Down
14 changes: 7 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
{
"name": "thepublicgood/analytics",
"description": "Send page views, requests and custom events to thepublicgood.analytics from PHP and Laravel.",
"name": "thepublicgood/trace",
"description": "Send page views, requests and custom events to thepublicgood.trace from PHP and Laravel.",
"type": "library",
"license": "MIT",
"keywords": ["analytics", "laravel", "privacy"],
"require": {
"php": "^8.3",
"php": "^8.5",
"ext-curl": "*",
"ext-json": "*"
},
"require-dev": {
"laravel/pint": "^1.18",
"orchestra/testbench": "^11.0",
"pestphp/pest": "^4.0",
"pestphp/pest": "^5.0",
"phpstan/phpstan": "^2.1"
},
"suggest": {
Expand All @@ -21,7 +21,7 @@
},
"autoload": {
"psr-4": {
"TPG\\Analytics\\": "src/"
"TPG\\Trace\\": "src/"
}
},
"autoload-dev": {
Expand All @@ -32,10 +32,10 @@
"extra": {
"laravel": {
"providers": [
"TPG\\Analytics\\Laravel\\AnalyticsServiceProvider"
"TPG\\Trace\\Laravel\\TraceServiceProvider"
],
"aliases": {
"Analytics": "TPG\\Analytics\\Laravel\\Analytics"
"Trace": "TPG\\Trace\\Laravel\\Trace"
}
}
},
Expand Down
21 changes: 11 additions & 10 deletions config/analytics-client.php → config/trace-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
| Property Key and Endpoint
|--------------------------------------------------------------------------
|
| Create a key on the property's Keys page. The endpoint is shown beside
| it, such as "https://analytics.example.com/api/v1".
| Create a key on the property's Keys page. Only set the endpoint when
| Trace is hosted somewhere else. It is shown beside the key, such as
| "https://trace.example.com/api/v1".
|
*/

'key' => env('ANALYTICS_KEY'),
'key' => env('TRACE_KEY'),

'endpoint' => env('ANALYTICS_ENDPOINT', 'https://visits.thepublicgood.dev/api/v1'),
'endpoint' => env('TRACE_ENDPOINT', 'https://trace.thepublicgood.dev/api/v1'),

/*
|--------------------------------------------------------------------------
Expand All @@ -25,19 +26,19 @@
|
*/

'enabled' => (bool) env('ANALYTICS_ENABLED', true),
'enabled' => (bool) env('TRACE_ENABLED', true),

/*
|--------------------------------------------------------------------------
| Verify SSL
|--------------------------------------------------------------------------
|
| Turn this off in local development when the analytics app is served
| Turn this off in local development when the Trace app is served
| with a self-signed certificate. Always leave it on in production.
|
*/

'verify_ssl' => (bool) env('ANALYTICS_VERIFY_SSL', true),
'verify_ssl' => (bool) env('TRACE_VERIFY_SSL', true),

/*
|--------------------------------------------------------------------------
Expand All @@ -49,7 +50,7 @@
|
*/

'track' => env('ANALYTICS_TRACK', 'pageviews'),
'track' => env('TRACE_TRACK', 'pageviews'),

'ignore' => [
'up',
Expand All @@ -67,11 +68,11 @@
|--------------------------------------------------------------------------
|
| Send the signed-in user's ID with each event, so the same person is
| counted once across devices. Analytics hashes it before storing it.
| counted once across devices. Trace hashes it before storing it.
|
*/

'identify_users' => (bool) env('ANALYTICS_IDENTIFY_USERS', false),
'identify_users' => (bool) env('TRACE_IDENTIFY_USERS', false),

/*
|--------------------------------------------------------------------------
Expand Down
Loading
Loading