From b35c5369e42aef2a077e83fd8e663770d321395f Mon Sep 17 00:00:00 2001 From: Warrick Bayman Date: Wed, 11 Nov 2026 11:35:18 +0200 Subject: [PATCH 1/3] Rename the package to thepublicgood/trace - Rename the package to thepublicgood/trace and the namespace to TPG\Trace. - Rename the facade, service provider and base exception to Trace, TraceServiceProvider and TraceException. - Rename the config to trace-client and the environment variables to TRACE_*. - Default the endpoint to https://trace.thepublicgood.dev/api/v1 in both the Client and the Laravel config, so only the key is required. - Require PHP 8.5 and upgrade Pest to v5. Co-Authored-By: Claude Opus 5.5 --- README.md | 58 +++++++++---------- composer.json | 14 ++--- ...{analytics-client.php => trace-client.php} | 21 +++---- src/Client.php | 41 +++++++------ src/Event.php | 2 +- src/EventType.php | 2 +- src/Exceptions/AnalyticsException.php | 10 ---- src/Exceptions/RequestFailedException.php | 8 +-- src/Exceptions/TraceException.php | 10 ++++ src/Exceptions/TransportException.php | 4 +- src/Laravel/Analytics.php | 57 ------------------ src/Laravel/RequestVisitor.php | 8 +-- src/Laravel/Trace.php | 57 ++++++++++++++++++ ...eProvider.php => TraceServiceProvider.php} | 32 +++++----- src/Laravel/TrackVisits.php | 26 ++++----- src/PropertySettings.php | 2 +- src/Transport/CurlTransport.php | 6 +- src/Transport/FakeTransport.php | 4 +- src/Transport/Response.php | 2 +- src/Transport/Transport.php | 6 +- src/Uuid.php | 2 +- src/Visitor.php | 6 +- src/VisitorCookie.php | 2 +- tests/ClientTest.php | 39 ++++++++----- tests/Laravel/TrackVisitsTest.php | 34 +++++------ tests/LaravelTestCase.php | 8 +-- 26 files changed, 240 insertions(+), 221 deletions(-) rename config/{analytics-client.php => trace-client.php} (75%) delete mode 100644 src/Exceptions/AnalyticsException.php create mode 100644 src/Exceptions/TraceException.php delete mode 100644 src/Laravel/Analytics.php create mode 100644 src/Laravel/Trace.php rename src/Laravel/{AnalyticsServiceProvider.php => TraceServiceProvider.php} (71%) diff --git a/README.md b/README.md index 994403a..86a0c85 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,44 @@ -# 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. @@ -45,49 +46,48 @@ Events are sent in one batch after the response has gone, so they don't slow you 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(); @@ -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); }); ``` diff --git a/composer.json b/composer.json index 4078990..16a84ae 100644 --- a/composer.json +++ b/composer.json @@ -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": { @@ -21,7 +21,7 @@ }, "autoload": { "psr-4": { - "TPG\\Analytics\\": "src/" + "TPG\\Trace\\": "src/" } }, "autoload-dev": { @@ -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" } } }, diff --git a/config/analytics-client.php b/config/trace-client.php similarity index 75% rename from config/analytics-client.php rename to config/trace-client.php index 36485a5..28fbf3b 100644 --- a/config/analytics-client.php +++ b/config/trace-client.php @@ -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'), /* |-------------------------------------------------------------------------- @@ -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), /* |-------------------------------------------------------------------------- @@ -49,7 +50,7 @@ | */ - 'track' => env('ANALYTICS_TRACK', 'pageviews'), + 'track' => env('TRACE_TRACK', 'pageviews'), 'ignore' => [ 'up', @@ -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), /* |-------------------------------------------------------------------------- diff --git a/src/Client.php b/src/Client.php index 5f0f2b7..5ecd291 100644 --- a/src/Client.php +++ b/src/Client.php @@ -1,20 +1,20 @@ ): void)|null + * @var (Closure(TraceException, list): void)|null */ protected ?Closure $onError; @@ -55,17 +60,17 @@ class Client /** * @param string $key The property key, starting with "ak_". - * @param string $endpoint The API endpoint shown next to the key, such as "https://analytics.example.com/api/v1". + * @param string $endpoint The API endpoint, only needed when Trace is hosted somewhere other than DEFAULT_ENDPOINT. * @param int $batchSize How many events to queue before they are sent. * @param int $maxQueueSize The most events to hold. The oldest are dropped beyond it. * @param int $retries How many times a batch is resent after a network error, rate limit or server error. * @param bool $flushOnShutdown Whether queued events are sent when the PHP process ends. - * @param (callable(AnalyticsException, list): void)|null $onError Called with each batch that couldn't be sent. + * @param (callable(TraceException, list): void)|null $onError Called with each batch that couldn't be sent. * @param bool $enabled Set to false to queue nothing and send nothing, such as in local development. */ public function __construct( protected readonly string $key, - string $endpoint, + string $endpoint = self::DEFAULT_ENDPOINT, protected readonly int $batchSize = self::MAX_BATCH_SIZE, protected readonly int $maxQueueSize = 1000, protected readonly int $retries = 1, @@ -74,7 +79,7 @@ public function __construct( ?Transport $transport = null, protected readonly bool $enabled = true, ) { - $this->endpoint = rtrim($endpoint, '/'); + $this->endpoint = rtrim($endpoint !== '' ? $endpoint : self::DEFAULT_ENDPOINT, '/'); $this->transport = $transport ?? new CurlTransport; $this->onError = $onError === null ? null : Closure::fromCallable($onError); @@ -168,7 +173,7 @@ public function flush(): bool try { $this->sendBatch($batch); - } catch (AnalyticsException $exception) { + } catch (TraceException $exception) { $sent = false; $this->report($exception, $batch); } @@ -210,7 +215,7 @@ public function queued(): array /** * Check the key and get the settings of its property. * - * @throws AnalyticsException when the key is wrong or the API can't be reached. + * @throws TraceException when the key is wrong or the API can't be reached. */ public function ping(): PropertySettings { @@ -281,7 +286,7 @@ protected function headers(): array return [ 'Authorization' => 'Bearer '.$this->key, 'Accept' => 'application/json', - 'User-Agent' => 'thepublicgood-analytics-php/'.self::VERSION, + 'User-Agent' => 'thepublicgood-trace-php/'.self::VERSION, ]; } @@ -290,7 +295,7 @@ protected function headers(): array * * @param list $batch */ - protected function report(AnalyticsException $exception, array $batch): void + protected function report(TraceException $exception, array $batch): void { try { if ($this->onError !== null) { @@ -299,7 +304,7 @@ protected function report(AnalyticsException $exception, array $batch): void return; } - error_log(sprintf('[analytics] Dropped %d event(s): %s', count($batch), $exception->getMessage())); + error_log(sprintf('[trace] Dropped %d event(s): %s', count($batch), $exception->getMessage())); } catch (Throwable) { // An error handler that throws must not break the app. } diff --git a/src/Event.php b/src/Event.php index 461c167..0447a49 100644 --- a/src/Event.php +++ b/src/Event.php @@ -1,6 +1,6 @@ json()['message'] ?? null; parent::__construct($message ?? sprintf( - 'The analytics API responded with %d%s', + 'The Trace API responded with %d%s', $response->status, is_string($apiMessage) ? ': '.$apiMessage : '.', ), $response->status); diff --git a/src/Exceptions/TraceException.php b/src/Exceptions/TraceException.php new file mode 100644 index 0000000..227adcb --- /dev/null +++ b/src/Exceptions/TraceException.php @@ -0,0 +1,10 @@ + $properties = [], ?\DateTimeInterface $occurredAt = null) - * @method static void screenview(string $screen, ?\TPG\Analytics\Visitor $visitor = null, array $properties = [], ?\DateTimeInterface $occurredAt = null) - * @method static void event(string $name, array $properties = [], ?\TPG\Analytics\Visitor $visitor = null, ?string $url = null, ?\DateTimeInterface $occurredAt = null) - * @method static void request(string $method, string $url, int $status, int $durationMs, ?\TPG\Analytics\Visitor $visitor = null, ?string $route = null, array $properties = [], ?\DateTimeInterface $occurredAt = null) - * @method static void track(\TPG\Analytics\Event $event) - * @method static bool flush() - * @method static list<\TPG\Analytics\Event> queued() - * @method static \TPG\Analytics\Visitor visitor(?\TPG\Analytics\Visitor $visitor = null) - * @method static \TPG\Analytics\PropertySettings ping() - * - * @see Client - */ -class Analytics extends Facade -{ - /** - * Record events instead of sending them, and get the fake transport to inspect them. - * - * Pass responses to control what the API answers, in order. Every other request is accepted. - */ - public static function fake(Response|TransportException ...$responses): FakeTransport - { - $transport = new FakeTransport(...$responses); - $app = static::getFacadeApplication(); - $existing = $app?->make(Client::class); - - $client = new Client( - key: 'ak_fake', - endpoint: 'https://analytics.invalid/api/v1', - flushOnShutdown: false, - transport: $transport, - ); - - if ($existing !== null) { - $client->resolveVisitorUsing(fn () => $existing->visitor()); - } - - static::swap($client); - - return $transport; - } - - protected static function getFacadeAccessor(): string - { - return Client::class; - } -} diff --git a/src/Laravel/RequestVisitor.php b/src/Laravel/RequestVisitor.php index 4c7ea3a..d789180 100644 --- a/src/Laravel/RequestVisitor.php +++ b/src/Laravel/RequestVisitor.php @@ -1,10 +1,10 @@ $properties = [], ?\DateTimeInterface $occurredAt = null) + * @method static void screenview(string $screen, ?\TPG\Trace\Visitor $visitor = null, array $properties = [], ?\DateTimeInterface $occurredAt = null) + * @method static void event(string $name, array $properties = [], ?\TPG\Trace\Visitor $visitor = null, ?string $url = null, ?\DateTimeInterface $occurredAt = null) + * @method static void request(string $method, string $url, int $status, int $durationMs, ?\TPG\Trace\Visitor $visitor = null, ?string $route = null, array $properties = [], ?\DateTimeInterface $occurredAt = null) + * @method static void track(\TPG\Trace\Event $event) + * @method static bool flush() + * @method static list<\TPG\Trace\Event> queued() + * @method static \TPG\Trace\Visitor visitor(?\TPG\Trace\Visitor $visitor = null) + * @method static \TPG\Trace\PropertySettings ping() + * + * @see Client + */ +class Trace extends Facade +{ + /** + * Record events instead of sending them, and get the fake transport to inspect them. + * + * Pass responses to control what the API answers, in order. Every other request is accepted. + */ + public static function fake(Response|TransportException ...$responses): FakeTransport + { + $transport = new FakeTransport(...$responses); + $app = static::getFacadeApplication(); + $existing = $app?->make(Client::class); + + $client = new Client( + key: 'ak_fake', + endpoint: 'https://trace.invalid/api/v1', + flushOnShutdown: false, + transport: $transport, + ); + + if ($existing !== null) { + $client->resolveVisitorUsing(fn () => $existing->visitor()); + } + + static::swap($client); + + return $transport; + } + + protected static function getFacadeAccessor(): string + { + return Client::class; + } +} diff --git a/src/Laravel/AnalyticsServiceProvider.php b/src/Laravel/TraceServiceProvider.php similarity index 71% rename from src/Laravel/AnalyticsServiceProvider.php rename to src/Laravel/TraceServiceProvider.php index cb95888..915cccd 100644 --- a/src/Laravel/AnalyticsServiceProvider.php +++ b/src/Laravel/TraceServiceProvider.php @@ -1,6 +1,6 @@ mergeConfigFrom(__DIR__.'/../../config/analytics-client.php', 'analytics-client'); + $this->mergeConfigFrom(__DIR__.'/../../config/trace-client.php', 'trace-client'); $this->app->scoped(Client::class, function (Application $app) { /** @var array{key: ?string, endpoint: ?string, enabled: bool, identify_users: bool, verify_ssl: bool} $config */ - $config = $app->make('config')->get('analytics-client'); + $config = $app->make('config')->get('trace-client'); $client = new Client( key: (string) $config['key'], - endpoint: (string) $config['endpoint'], + endpoint: (string) $config['endpoint'] ?: Client::DEFAULT_ENDPOINT, flushOnShutdown: false, transport: new CurlTransport(verifySsl: $config['verify_ssl']), - onError: fn (AnalyticsException $exception, array $batch) => Log::warning('Analytics dropped '.count($batch).' event(s).', ['exception' => $exception]), - enabled: $config['enabled'] && filled($config['key']) && filled($config['endpoint']), + onError: fn (TraceException $exception, array $batch) => Log::warning('Trace dropped '.count($batch).' event(s).', ['exception' => $exception]), + enabled: $config['enabled'] && filled($config['key']), ); return $client->resolveVisitorUsing(function () use ($app, $config): ?Visitor { @@ -51,7 +51,7 @@ public function register(): void }); }); - $this->app->alias(Client::class, 'analytics-client'); + $this->app->alias(Client::class, 'trace-client'); } /** @@ -61,8 +61,8 @@ public function boot(): void { if ($this->app->runningInConsole()) { $this->publishes([ - __DIR__.'/../../config/analytics-client.php' => config_path('analytics-client.php'), - ], 'analytics-client-config'); + __DIR__.'/../../config/trace-client.php' => config_path('trace-client.php'), + ], 'trace-client-config'); } EncryptCookies::except(VisitorCookie::DEFAULT_NAME); diff --git a/src/Laravel/TrackVisits.php b/src/Laravel/TrackVisits.php index 5ec9cbe..6d18474 100644 --- a/src/Laravel/TrackVisits.php +++ b/src/Laravel/TrackVisits.php @@ -1,6 +1,6 @@ attributes->set('analytics-client.started-at', microtime(true)); + $request->attributes->set('trace-client.started-at', microtime(true)); if (! $this->enabled() || ! $this->shouldTrack($request)) { return $next($request); @@ -83,7 +83,7 @@ public function terminate(Request $request, Response $response): void return; } - if ($this->config->get('analytics-client.track') === 'requests') { + if ($this->config->get('trace-client.track') === 'requests') { $this->client->request( method: $request->method(), url: $request->fullUrl(), @@ -132,7 +132,7 @@ protected function isPrefetch(Request $request): bool protected function shouldTrack(Request $request): bool { /** @var list $ignore */ - $ignore = $this->config->get('analytics-client.ignore', []); + $ignore = $this->config->get('trace-client.ignore', []); return $ignore === [] || ! $request->is(...$ignore); } @@ -142,7 +142,7 @@ protected function shouldTrack(Request $request): bool */ protected function enabled(): bool { - return $this->config->get('analytics-client.enabled') && filled($this->config->get('analytics-client.key')) && filled($this->config->get('analytics-client.endpoint')); + return $this->config->get('trace-client.enabled') && filled($this->config->get('trace-client.key')); } /** @@ -150,7 +150,7 @@ protected function enabled(): bool */ protected function settings(): PropertySettings { - $cacheKey = 'analytics-client:settings:'.hash('xxh128', (string) $this->config->get('analytics-client.key')); + $cacheKey = 'trace-client:settings:'.hash('xxh128', (string) $this->config->get('trace-client.key')); $cached = $this->cache->get($cacheKey); if (is_array($cached)) { @@ -159,8 +159,8 @@ protected function settings(): PropertySettings try { $settings = $this->client->ping(); - $seconds = (int) $this->config->get('analytics-client.settings_cache_seconds', 3600); - } catch (AnalyticsException) { + $seconds = (int) $this->config->get('trace-client.settings_cache_seconds', 3600); + } catch (TraceException) { $settings = new PropertySettings(name: '', type: '', persistentVisitors: false); $seconds = self::FAILED_LOOKUP_CACHE_SECONDS; } @@ -185,7 +185,7 @@ protected function routePattern(Request $request): ?string */ protected function durationMs(Request $request): int { - $startedAt = $request->attributes->get('analytics-client.started-at'); + $startedAt = $request->attributes->get('trace-client.started-at'); $startedAt = is_float($startedAt) ? $startedAt : (defined('LARAVEL_START') ? LARAVEL_START : microtime(true)); return (int) round((microtime(true) - $startedAt) * 1000); diff --git a/src/PropertySettings.php b/src/PropertySettings.php index d5548ea..181eaed 100644 --- a/src/PropertySettings.php +++ b/src/PropertySettings.php @@ -1,6 +1,6 @@ 'ak_test', 'endpoint' => 'https://analytics.test/api/v1/', 'flushOnShutdown' => false, 'transport' => $transport, ...$options]); + return new Client(...['key' => 'ak_test', 'endpoint' => 'https://trace.test/api/v1/', 'flushOnShutdown' => false, 'transport' => $transport, ...$options]); } test('queued events are sent together when flushed', function () { @@ -34,7 +34,7 @@ function fakeClient(FakeTransport $transport, mixed ...$options): Client $request = $transport->requests[0]; expect($request['method'])->toBe('POST') - ->and($request['url'])->toBe('https://analytics.test/api/v1/events') + ->and($request['url'])->toBe('https://trace.test/api/v1/events') ->and($request['headers'])->toMatchArray(['Authorization' => 'Bearer ak_test', 'Content-Type' => 'application/json']); [$pageview, $event, $apiRequest, $screenview] = $transport->events(); @@ -99,7 +99,7 @@ function fakeClient(FakeTransport $transport, mixed ...$options): Client test('batches the API rejects are reported and dropped without a retry', function () { $transport = new FakeTransport(new Response(422, '{"message":"The events.0.url field must be a valid URL."}')); $reported = []; - $client = fakeClient($transport, onError: function (AnalyticsException $exception, array $batch) use (&$reported) { + $client = fakeClient($transport, onError: function (TraceException $exception, array $batch) use (&$reported) { $reported[] = [$exception, $batch]; }); @@ -110,7 +110,7 @@ function fakeClient(FakeTransport $transport, mixed ...$options): Client ->and($client->queued())->toBeEmpty() ->and($reported)->toHaveCount(1) ->and($reported[0][0])->toBeInstanceOf(RequestFailedException::class) - ->and($reported[0][0]->getMessage())->toBe('The analytics API responded with 422: The events.0.url field must be a valid URL.') + ->and($reported[0][0]->getMessage())->toBe('The Trace API responded with 422: The events.0.url field must be a valid URL.') ->and($reported[0][1])->toHaveCount(1); }); @@ -181,12 +181,12 @@ function fakeClient(FakeTransport $transport, mixed ...$options): Client expect($settings->name)->toBe('Storefront') ->and($settings->persistentVisitors)->toBeTrue() ->and($settings->visitorCookie)->toBe('_vid') - ->and($transport->requests[0]['url'])->toBe('https://analytics.test/api/v1/ping'); + ->and($transport->requests[0]['url'])->toBe('https://trace.test/api/v1/ping'); }); test('ping throws when the key is wrong', function () { fakeClient(new FakeTransport(new Response(401, '{"message":"Unauthenticated."}')))->ping(); -})->throws(RequestFailedException::class, 'The analytics API responded with 401: Unauthenticated.'); +})->throws(RequestFailedException::class, 'The Trace API responded with 401: Unauthenticated.'); test('the visitor is read from the request globals', function () { $visitor = Visitor::fromGlobals( @@ -204,3 +204,16 @@ function fakeClient(FakeTransport $transport, mixed ...$options): Client test('visitor cookies that were tampered with are ignored', function () { expect(Visitor::fromGlobals(server: [], cookies: ['_a_vid' => 'someone-else'])->anonymousId)->toBeNull(); }); + +test('events go to the hosted endpoint when none is given', function (string $endpoint) { + $transport = new FakeTransport; + $client = new Client(key: 'ak_test', endpoint: $endpoint, flushOnShutdown: false, transport: $transport); + + $client->event('signup'); + $client->flush(); + + expect($transport->requests[0]['url'])->toBe('https://trace.thepublicgood.dev/api/v1/events'); +})->with([ + 'default' => [Client::DEFAULT_ENDPOINT], + 'empty' => [''], +]); diff --git a/tests/Laravel/TrackVisitsTest.php b/tests/Laravel/TrackVisitsTest.php index 3de0b5c..2ab3402 100644 --- a/tests/Laravel/TrackVisitsTest.php +++ b/tests/Laravel/TrackVisitsTest.php @@ -3,11 +3,11 @@ use Illuminate\Auth\GenericUser; use Illuminate\Container\Container; use Illuminate\Support\Facades\Route; -use TPG\Analytics\Client; -use TPG\Analytics\Laravel\Analytics; -use TPG\Analytics\Laravel\TrackVisits; -use TPG\Analytics\Transport\FakeTransport; -use TPG\Analytics\Transport\Response; +use TPG\Trace\Client; +use TPG\Trace\Laravel\Trace; +use TPG\Trace\Laravel\TrackVisits; +use TPG\Trace\Transport\FakeTransport; +use TPG\Trace\Transport\Response; /** * A ping response for a property with the given visitor identification. @@ -29,7 +29,7 @@ function pingResponse(string $identification = 'cookieless'): Response Route::get('/up', fn () => response('

Up

')); Route::get('/api/users/{user}', fn (string $user) => ['id' => $user]); Route::post('/signup', function () { - Analytics::event('signup', ['plan' => 'pro']); + Trace::event('signup', ['plan' => 'pro']); return response('

Welcome

'); }); @@ -37,7 +37,7 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('page views are recorded with the visitor', function () { - $transport = Analytics::fake(pingResponse()); + $transport = Trace::fake(pingResponse()); $this->withHeaders(['User-Agent' => 'Mozilla/5.0', 'Referer' => 'https://google.com/']) ->get('/pricing?utm_source=newsletter') @@ -55,7 +55,7 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('requests that are not page views are skipped', function (string $uri, array $headers) { - $transport = Analytics::fake(pingResponse()); + $transport = Trace::fake(pingResponse()); $this->withHeaders($headers)->get($uri); @@ -69,8 +69,8 @@ function pingResponse(string $identification = 'cookieless'): Response ]); test('API properties record every request with its route pattern', function () { - config(['analytics-client.track' => 'requests']); - $transport = Analytics::fake(pingResponse()); + config(['trace-client.track' => 'requests']); + $transport = Trace::fake(pingResponse()); $this->getJson('/api/users/7')->assertOk(); $this->getJson('/missing')->assertNotFound(); @@ -89,7 +89,7 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('persistent properties give new visitors a cookie and recognise them afterwards', function () { - $transport = Analytics::fake(pingResponse('persistent')); + $transport = Trace::fake(pingResponse('persistent')); $response = $this->get('/pricing')->assertCookieNotExpired('_a_vid'); $visitorId = $response->getCookie('_a_vid', decrypt: false)->getValue(); @@ -101,7 +101,7 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('the property settings are cached between requests', function () { - $transport = Analytics::fake(pingResponse('persistent')); + $transport = Trace::fake(pingResponse('persistent')); $this->get('/pricing'); $this->get('/pricing'); @@ -110,8 +110,8 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('events tracked during a request belong to its visitor', function () { - config(['analytics-client.identify_users' => true]); - $transport = Analytics::fake(pingResponse()); + config(['trace-client.identify_users' => true]); + $transport = Trace::fake(pingResponse()); $this->actingAs(new GenericUser(['id' => 42])) ->withHeaders(['User-Agent' => 'Mozilla/5.0']) @@ -130,8 +130,8 @@ function pingResponse(string $identification = 'cookieless'): Response }); test('nothing is tracked without a key', function () { - config(['analytics-client.key' => null]); - $transport = Analytics::fake(pingResponse('persistent')); + config(['trace-client.key' => null]); + $transport = Trace::fake(pingResponse('persistent')); $this->get('/pricing')->assertCookieMissing('_a_vid'); @@ -145,7 +145,7 @@ function pingResponse(string $identification = 'cookieless'): Response $sandbox->instance(Container::class, $sandbox); $sandbox->instance(Client::class, new Client( key: 'ak_fake', - endpoint: 'https://analytics.invalid/api/v1', + endpoint: 'https://trace.invalid/api/v1', flushOnShutdown: false, transport: $transport, )); diff --git a/tests/LaravelTestCase.php b/tests/LaravelTestCase.php index b7693e9..b5252f5 100644 --- a/tests/LaravelTestCase.php +++ b/tests/LaravelTestCase.php @@ -3,7 +3,7 @@ namespace Tests; use Orchestra\Testbench\TestCase; -use TPG\Analytics\Laravel\AnalyticsServiceProvider; +use TPG\Trace\Laravel\TraceServiceProvider; abstract class LaravelTestCase extends TestCase { @@ -12,13 +12,13 @@ abstract class LaravelTestCase extends TestCase */ protected function getPackageProviders($app): array { - return [AnalyticsServiceProvider::class]; + return [TraceServiceProvider::class]; } protected function defineEnvironment($app): void { - $app['config']->set('analytics-client.key', 'ak_test'); - $app['config']->set('analytics-client.endpoint', 'https://analytics.test/api/v1'); + $app['config']->set('trace-client.key', 'ak_test'); + $app['config']->set('trace-client.endpoint', 'https://trace.test/api/v1'); $app['config']->set('cache.default', 'array'); } } From 7a2b80ffaf27f9fac82461f467482cd0f9ed643e Mon Sep 17 00:00:00 2001 From: Warrick Bayman Date: Wed, 11 Nov 2026 11:36:01 +0200 Subject: [PATCH 2/3] gitignore update --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 3797366..58cdd63 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /vendor /.phpunit.cache +/.idea composer.lock .DS_Store From 79229c7a594a33eb45ae41c76caa04d58c495d3b Mon Sep 17 00:00:00 2001 From: Warrick Bayman Date: Wed, 11 Nov 2026 11:38:12 +0200 Subject: [PATCH 3/3] Run the tests in GitHub Actions Runs Pest on PHP 8.5 against the lowest and highest allowed dependencies for pushes to main and for pull requests. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..57398fc --- /dev/null +++ b/.github/workflows/tests.yml @@ -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