Skip to content

Commit

Permalink
Only register event listener when the service is configured
Browse files Browse the repository at this point in the history
Also added helper methods for checking if the service is enabled / configured
  • Loading branch information
LukeTowers committed Dec 12, 2023
1 parent 8a1d7f2 commit 0dfc4c8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
18 changes: 10 additions & 8 deletions src/GA4.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,15 @@ class GA4
'google_',
];

public function __construct()
public function isConfigured(): bool
{
if (config('ga4-event-tracking.measurement_id') === null
|| config('ga4-event-tracking.api_secret') === null
) {
throw new \Exception('GA4 cannot be used without a Measurement ID and API Secret. Check your .env file or config/ga4-event-tracking.php.');
}
return config('ga4-event-tracking.measurement_id') !== null
&& config('ga4-event-tracking.api_secret') !== null;
}

public function isEnabled(): bool
{
return $this->isConfigured() && config('ga4-event-tracking.is_enabled', true);
}

public function setClientId(string $clientId): static
Expand Down Expand Up @@ -155,10 +157,10 @@ public function sendEvent(array $eventData): array
*/
public function sendEvents(array $events): array
{
if (!config('ga4-event-tracking.is_enabled', true)) {
if (!$this->isEnabled()) {
return [
'status' => false,
'message' => 'GA4 Event Tracking is disabled.',
'message' => 'GA4 Event Tracking is not configured.',
];
}

Expand Down
9 changes: 8 additions & 1 deletion src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use DevPro\GA4EventTracking\Http\ClientIdSession;
use DevPro\GA4EventTracking\Http\StoreClientIdInSession;
use DevPro\GA4EventTracking\Listeners\DispatchAnalyticsJob;
use GA4;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
Expand All @@ -29,7 +30,13 @@ public function boot(): void
$this->bootForConsole();
}

Event::listen(ShouldBroadcastToAnalytics::class, DispatchAnalyticsJob::class);
// Only register the listener if the measurement_id and api_secret are set
// to avoid unnecessary overhead.
if (config('ga4-event-tracking.measurement_id') !== null
&& !config('ga4-event-tracking.api_secret') !== null
) {
Event::listen(ShouldBroadcastToAnalytics::class, DispatchAnalyticsJob::class);
}

Blade::directive('sendGA4ClientID', function () {
return "<?php echo view('ga4-event-tracking::sendClientID'); ?>";
Expand Down

0 comments on commit 0dfc4c8

Please sign in to comment.